Typescript 定义类型字符串|在字符串数组类型中未定义
我有以下自定义类型:Typescript 定义类型字符串|在字符串数组类型中未定义,typescript,types,Typescript,Types,我有以下自定义类型: hero?: string power?: string 我想将这些类型添加到数组中,数组是另一个类型的一部分 type Superheroes = { character: string[] | [] villains: number | null city: string } 当我尝试使用该类型(见下文)时,我得到以下错误Typescript:type'string | undefined'不可分配给type'string' return { character:
hero?: string
power?: string
我想将这些类型添加到数组中,数组是另一个类型的一部分
type Superheroes = {
character: string[] | []
villains: number | null
city: string
}
当我尝试使用该类型(见下文)时,我得到以下错误Typescript:type'string | undefined'不可分配给type'string'
return {
character: [hero, power],
villains: 2 || null,
city: 'new york' || null
}
在字符数组中定义英雄和力量类型的正确方法是什么?您可以将类型更改为:
city: string || null
或者将城市属性的赋值更改为:
city: 'new york'
没有数组或null。要使其可分配,您应该定义超级英雄的类型如下:
类型超级英雄={
字符:(字符串|未定义)[]
恶棍:数字|空
城市:字符串
}
或者如果字符
数组中的元素始终不超过两个:
类型超级英雄={
字符:[字符串?,字符串?]
恶棍:数字|空
城市:字符串
}
能否在示例please tsplay.dev/mL9MKW中进行编辑?问题在于
字符
数组中的hero
和power
类型。city
作为一个数组是一个拼写错误,现在可以修复了。我看到您在没有初始化的情况下为hero?:string
和power?:string添加问号,这可能是未定义的,我认为您可以尝试初始化hero
和power
如下:hero?:string=';幂?:字符串=“”代码>以避免错误。