相关: https :
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
}
使用tslint.json
配置:
(使用test/rules/strict-type-predicates/strict-null-checks/tsconfig.json
)
(A 是实际的,E 是预期的,B 是两者)
{
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.]
}
(运行示例在这里:https://github.com/ypresto/tslint/tree/strict-type-predicates-index-type )
更简单的例子:
const foo: { [key: string]: string } = {}
if (foo.bar === undefined) {
// blah
}
会产生
ERROR: /Users/yuya/repo/github.com-private/codetakt/pf-user-admin/client/test.ts[2, 5]: Expression is always false.
但预计不会出现错误。
tslint 不是添加这种特殊处理的正确位置。 这需要改变打字稿的类型推断。 https://github.com/Microsoft/TypeScript/issues/13778
如果您总是在使用该值之前检查 undefined,您还可以定义您的索引签名以包含undefined
;
const foo: { [key: string]: string | undefined } = {}
+1 to ajaff - 结束,因为这是 TypeScript 的一个设计点。
最有用的评论
更简单的例子:
会产生
但预计不会出现错误。