TYPESCRIPT-如何在TYPESCRIPT对象的每个属性中允许更多类型



我的项目中有一个对象。这是模式:

IObject : {
prop1: number;
prop2: number;
}

这是我想要的90%的用法的打字方式。但也有一些实例要求我为每个属性返回一个字符串。因此,对于一些实例,我想要一个返回的接口:

object: IObjectWithStrings // Here I want to add string to each property as acceptable type.
// Something like
object: IObjects extends string

我该怎么做??我可以为此创建一个新的interface,但我宁愿拥有原始的interface并扩展它。谢谢!!

您可以使用泛型来完成此操作。在本例中,您可以定义一个基本类型IObject<T>,其中T表示动态类型,如下所示:

type IObject<T> = {
prop1: T;
prop2: T;
}

然后,您可以直接使用IObject<number>IObject<number | string>,其中number | string表示"prop1可以是两者之一"(Union类型(,或者您可以使用基本类型IObject<T>:定义其他类型

type IObjectNumber = IObject<number>;
type IObjectWithString = IObject<number | string>;
const objNum: IObjectNumber = { prop1: 10, prop2: 'abc' } // this will throw error
const objNumStr: IObjectWithString = { prop1: 10, prop2: 'abc' } // this will not throw error

您可以根据现有类型创建另一种类型:

type IObject = {
prop1: number;
prop2: number;
}
type IObjectString = {
[K in keyof IObject]: string 
}
type IObjectStringOrOriginal = {
[K in keyof IObject]: string | IObject[K]
}

最新更新