简体   繁体   中英

Typescript OR types

I have a variable which can be either of Array<{name:"string"}> or 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 "

How do I do this then?

Type Array<{name: string;}> | string Array<{name: string;}> | string make TypeScript compiler not sure whether the variable is Array<{name: string;} or 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;}

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 is Array, Object. You have to add index reference such as nameObj[0].name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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