[英]Typescript OR types
I have a variable which can be either of Array<{name:"string"}>
or string
. 我有一个变量,可以是
Array<{name:"string"}>
或string
。
I attempted this: 我试图这样做:
let nameObj:Array<{name:"string"}> | string;
But when I do nameObj[0].name
, the compiler gives error saying: "Property 'name' does not exist on type 'string "
但是,当我执行
nameObj[0].name
,编译器给出错误提示: "Property 'name' does not exist on type 'string "
How do I do this then? 那我该怎么做呢?
Type Array<{name: string;}> | string
键入
Array<{name: string;}> | string
Array<{name: string;}> | string
make TypeScript compiler not sure whether the variable is Array<{name: string;}
or string
. Array<{name: string;}> | string
使TypeScript编译器不确定该变量是Array<{name: string;}
还是string
。 It is not safe in runtime. 在运行时不安全。 You have to specify the output for each case, or specify one type if you know that the variable always is
string
or Array<{name: string;}
您必须为每种情况指定输出,或者如果您知道变量始终为
string
或Array<{name: string;}
,则必须指定一种类型
let nameObj: Array<{ name: string; }> | string;
const name: string = typeof nameObj === "string"
? nameObj : nameObj[0].name;
let nameObj: Array<{ name: string; }> | string;
// you are sure this variable is Array
const name = (Array<{ name: string; }> nameObj)[0].name;
However your code nameObj.name
is wrong. 但是,您的代码名
nameObj.name
是错误的。 nameObj is Array, Object. nameObj是数组,对象。 You have to add index reference such as
nameObj[0].name
您必须添加索引引用,例如
nameObj[0].name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.