简体   繁体   中英

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]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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