首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在属性对象上使用带有条件的typescript正确键入对象

在TypeScript中,您可以为对象属性定义条件类型

假设您有一个类型Person,您希望根据某个条件为属性添加类型:

代码语言:javascript
复制
interface Person {
  name: string;
  age: number;
  isStudent: boolean;
}

现在,您想要创建一个类型ConditionalPerson,它具有一个条件类型属性status,该属性仅当isStudenttrue时存在:

代码语言:javascript
复制
type ConditionalPerson<T extends Person> = T & (
  T['isStudent'] extends true ? { status: string } : {}
);

在这个例子中,我们使用了映射类型和条件类型。ConditionalPerson类型接受一个泛型参数T,该参数扩展了Person类型。然后,我们使用条件类型检查isStudent属性是否为true。如果是,则将status属性添加到类型中。

现在,您可以使用ConditionalPerson类型创建对象:

代码语言:javascript
复制
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属性,因为它仅当isStudenttrue时才存在。

这就是如何在TypeScript中使用条件类型为对象属性添加类型。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券