如何从未知类型的对象获取属性?
我尝试检查我的unknown
类型变量是否为null
(确定),如果我的变量为typeOf
object
(确定),但是我不能检查是否hasOwnProperty()
。 TS表示即使我刚刚检查了null
,也可能const config: unknown = returnsUnknown();
// ↓ Error, TS2531: Object is possibly 'null'.
if (config !== null && typeof config === 'object' && config.hasOwnProperty("someProperty")) {
console.log("Whoah! Here is my property!", config.someProperty);
}
。
if (config !== null && typeof config === 'object' && config?.hasOwnProperty("someProperty"))
{
// TS2339: Property 'someProperty' does not exist on type 'object'.
console.log(config.someProperty);
// TS7053: Property 'someProperty' does not exist on type '{}'.
console.log(config["someProperty"]);
}
编辑:正如@krantni所建议的那样,可选链接有助于修复我的if语句。
[assembly: AssemblyVersion("4.0.3.0")]
我正在使用TypeScript V 3.9.5
答案 0 :(得分:0)
在打字稿3.7中,您可以使用可选的链接,它将检查是否为null: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining
if (
config !== null &&
typeof config === 'object' &&
config?.hasOwnProperty('someProperty')
) {
console.log('Whoah! Here is my property!', config['someProperty']);
}