Relacionado a: 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
}
com configuração tslint.json
:
(Usando test/rules/strict-type-predicates/strict-null-checks/tsconfig.json
)
(A é real, E é esperado, B é 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.]
}
(O exemplo de execução está aqui: https://github.com/ypresto/tslint/tree/strict-type-predicates-index-type)
Exemplo mais simples:
const foo: { [key: string]: string } = {}
if (foo.bar === undefined) {
// blah
}
vai produzir
ERROR: /Users/yuya/repo/github.com-private/codetakt/pf-user-admin/client/test.ts[2, 5]: Expression is always false.
mas nenhum erro é esperado.
tslint não é o lugar certo para adicionar esse tipo de tratamento especial. Isso exigiria uma mudança na inferência de tipo do texto datilografado. https://github.com/Microsoft/TypeScript/issues/13778
Se você sempre verificar undefined antes de usar o valor, também poderá definir sua assinatura de índice para incluir undefined
;
const foo: { [key: string]: string | undefined } = {}
+1 para ajafff - fechando, pois este é um ponto de design do TypeScript.
Comentários muito úteis
Exemplo mais simples:
vai produzir
mas nenhum erro é esperado.