只需更改一个属性即可将现有类型转换为新类型



如何通过一个属性更改将现有类型转换为新类型?

Typesctipt沙盒

示例:

type SomeComplexType = string // just for example
// cannot be changed
type Options<T> = {
opt1: boolean | undefined;
opt2: number;
opt3?: SomeComplexType;
opt4: T
}
// Can be changed
// How to change opt1 to accept only true and infer other option types?
type Keys = keyof Options<any>
let r: { [K in Keys]: K extends 'opt1' ? true : any }
// Good (should work)
r = { opt1: true, opt2: 2, opt3: '1', opt4: 1 }
r = { opt1: true, opt2: 2, opt3: '1', opt4: 'str' }
// Bad (should be error)
r = { opt1: false, opt2: 1, opt3: 'str', opt4: 1 } // opt1 should be true
r = { opt1: true, opt2: 'str', opt3: 'str', opt4: 1 } // opt2 should be number
r = { opt1: true, opt2: 'str', opt3: 1, opt4: 1 } // opt3 should be 

如果您有一个对象类型O,并且想要创建一个新类型,其中除了键opt1处的属性应该是true之外,所有的proptery键和值都是相同的,您可以这样写:

{ [K in keyof O]: K extends 'opt1' ? true : O[K] }

语法CCD_ 4是索引访问;具有类型为CCD_ 6"的密钥的CCD_;。

然后,您的示例应该按需工作,(假设OOptions<any>(:

// Good 
r = { opt1: true, opt2: 2, opt3: '1', opt4: 1 } // okay
r = { opt1: true, opt2: 2, opt3: '1', opt4: 'str' } // okay
// Bad 
r = { opt1: false, opt2: 1, opt3: 'str', opt4: 1 } // error!
r = { opt1: true, opt2: 'str', opt3: 'str', opt4: 1 } // error!
r = { opt1: true, opt2: 'str', opt3: 1, opt4: 1 } // error!

游乐场链接到代码

最新更新