【发布时间】:2020-02-06 05:25:11
【问题描述】:
我如何让 TypeScript 知道一个函数验证了一个项目是否包含给定的键?
例如:
function doesItemHaveKey(item: any, key: string): boolean {
return typeof item === 'object' && item !== null && typeof item[key] !== 'undefined';
}
interface testInterface {
optional?: string;
some: string;
}
let testObj: testInterface = {
some: 'value'
};
if (doesItemHaveKey(testObj, 'some')) {
// Do something with testObj.some
// TypeScript throws errors because `testObj.some` could be undefined
}
我尝试过的事情:
if (doesItemHaveKey(testObj, 'some') && typeof testObj.some !== 'undefined') {
// This works, but duplicates the typeof check
}
function doesItemHaveKey(item: any, key: string): key is keyof item
/**
* A type predicate's type must be assignable to its parameter's type.
* Type 'string | number | symbol' is not assignable to type 'string'.
* Type 'number' is not assignable to type 'string'.
**/
【问题讨论】:
-
我想你忘了一个?在
some上,否则some不是可能未定义的类型 -
即使它是可选的,
testObj.some也不会在该代码中给出类型错误。
标签: typescript