[英]How to make the TS compiler know an unknown variable has some properties (without the usage of `any` type)
function f(): unknown {
return {abc: "ABC"};
}
const a = f();
if (a && a instanceof Object && a.hasOwnProperty("abc")) {
console.log(a.abc);
}
I have a variable a
which is the unknown
type at first (>= TypeScript 3.0). 我有一个变量
a
,起初是unknown
类型(> = TypeScript 3.0)。 I want to use the abc
property of a
inside an if statement when a
has the property. 我想在
a
具有该属性a
在if语句中使用abc
属性。
However, as the above VS code screenshot shows, the TypeScript compiler gives the TS2339
error even though I checked a.hasOwnProperty("abc")
in the if condition. 但是,如上面的VS代码屏幕截图所示,即使我在if条件下检查了
a.hasOwnProperty("abc")
,TypeScript编译器TS2339
出现TS2339
错误。
Property 'abc' does not exist on type 'object'.
类型“对象”上不存在属性“ abc”。 ts(2339)
TS(2339)
I know that I can bypass this error by casting a
to any
type, but it will make the compiler ignore the typos of members' names, and it will be bad if there are many properties in a
and many things to do with the variable a
. 我知道我可以通过铸造绕过这个错误
a
到any
类型的,但它将使编译器忽略的成员的姓名拼写错误,如果有许多特性将是糟糕的a
,很多事情做的变量a
。
Is there a way for the TypeScript compiler to know that a
has certain properties? TypeScript编译器是否可以知道
a
具有某些属性?
You can use { [index: string]: unknown }
instead of unknown
to tell TypeScript your object is a dictionary of unknown properties. 您可以使用
{ [index: string]: unknown }
而不是unknown
来告诉TypeScript您的对象是未知属性的字典。
declare const unfamiliar: { [index: string]: unknown };
if ('foo' in unfamiliar) {
unfamiliar.foo;
}
The error comes from the assertion that a
is an Object
. 错误来自于断言
a
是Object
。 The Object
type does not contain abc
so the following assertion does not make a difference. Object
类型不包含abc
因此以下断言没有区别。
If you only keep the a.hasOwnProperty()
assertion it should work. 如果仅保留
a.hasOwnProperty()
断言,则它应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.