Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 定义类型字符串|在字符串数组类型中未定义_Typescript_Types - Fatal编程技术网

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=';幂?:字符串=“”以避免错误。