简体   繁体   English

打字稿或类型

[英]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;} 您必须为每种情况指定输出,或者如果您知道变量始终为stringArray<{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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM