Relacionado con: https://github.com/Microsoft/TypeScript/issues/13778
declare function get<T>(): T;
// index types
{
get<{ [key: string]: string }>()['foo'] === undefined
get<{ [key: string]: string }>()['foo'] === null
get<{ [key: string]: string }>()['foo'] == undefined
get<{ [key: string]: string }>()['foo'] == null
get<{ [index: number]: string }>()[0] === undefined
get<{ [index: number]: string }>()[0] === null
get<{ [index: number]: string }>()[0] == undefined
get<{ [index: number]: string }>()[0] == null
}
con tslint.json
configuración:
(Usando test/rules/strict-type-predicates/strict-null-checks/tsconfig.json
)
(A es real, E es esperado, B es ambos)
{
get<{ [key: string]: string }>()['foo'] === undefined
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
get<{ [key: string]: string }>()['foo'] === null
B: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
get<{ [key: string]: string }>()['foo'] == undefined
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
E: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Use '=== undefined' instead.]
get<{ [key: string]: string }>()['foo'] == null
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
E: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Use '=== undefined' instead.]
get<{ [index: number]: string }>()[0] === undefined
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
get<{ [index: number]: string }>()[0] === null
B: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
get<{ [index: number]: string }>()[0] == undefined
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
E: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Use '=== undefined' instead.]
get<{ [index: number]: string }>()[0] == null
A: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Expression is always false.]
E: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Use '=== undefined' instead.]
}
(El ejemplo de ejecución está aquí: https://github.com/ypresto/tslint/tree/strict-type-predicates-index-type)
Ejemplo más simple:
const foo: { [key: string]: string } = {}
if (foo.bar === undefined) {
// blah
}
Producirá
ERROR: /Users/yuya/repo/github.com-private/codetakt/pf-user-admin/client/test.ts[2, 5]: Expression is always false.
pero no se espera ningún error.
tslint no es el lugar adecuado para agregar este tipo de manejo especial. Esto requeriría un cambio en la inferencia de tipos de mecanografiado. https://github.com/Microsoft/TypeScript/issues/13778
Si siempre verifica indefinido antes de usar el valor, también puede definir su firma de índice para incluir undefined
;
const foo: { [key: string]: string | undefined } = {}
+1 a ajafff - cerrando ya que este es un punto de diseño de TypeScript.
Comentario más útil
Ejemplo más simple:
Producirá
pero no se espera ningún error.