在TypeScript中,您可以为对象属性定义条件类型
假设您有一个类型Person
,您希望根据某个条件为属性添加类型:
interface Person {
name: string;
age: number;
isStudent: boolean;
}
现在,您想要创建一个类型ConditionalPerson
,它具有一个条件类型属性status
,该属性仅当isStudent
为true
时存在:
type ConditionalPerson<T extends Person> = T & (
T['isStudent'] extends true ? { status: string } : {}
);
在这个例子中,我们使用了映射类型和条件类型。ConditionalPerson
类型接受一个泛型参数T
,该参数扩展了Person
类型。然后,我们使用条件类型检查isStudent
属性是否为true
。如果是,则将status
属性添加到类型中。
现在,您可以使用ConditionalPerson
类型创建对象:
const student: ConditionalPerson<{ name: string; age: number; isStudent: true }> = {
name: 'Alice',
age: 20,
isStudent: true,
status: 'Freshman',
};
const nonStudent: ConditionalPerson<{ name: string; age: number; isStudent: false }> = {
name: 'Bob',
age: 30,
isState: false,
};
注意,在nonStudent
对象中,TypeScript不会要求status
属性,因为它仅当isStudent
为true
时才存在。
这就是如何在TypeScript中使用条件类型为对象属性添加类型。
领取专属 10元无门槛券
手把手带您无忧上云