简体   繁体   English

如何使用为某些字段指定的值创建子类型并消除 typescript 中的可选成员

[英]How to create a sub type with values specified for some fields and eliminate optional member in typescript

interface A{ 
prop1:string,
prop2:boolean,
prop3?:boolean
}
interface B extends A{
prop1='some real value',
prop2:boolean
}

I want to do something like above, I would also like to know if something similar can be achieved through type as well.我想做上面那样的事情,我也想知道是否也可以通过类型来实现类似的事情。 Any help appreciated.任何帮助表示赞赏。

Assuming that your goal is to remove the optional properties using types instead of interfaces you could do something like this:假设您的目标是使用类型而不是接口删除可选属性,您可以这样做:

type A = { 
  prop1: string,
  prop2: boolean,
  prop3?: boolean
}

type B = {
    [K in keyof A as A[K] extends Required<A>[K] ? K : never]: A[K]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM