如何通过一个属性更改将现有类型转换为新类型?
例子:
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
,您可以这样编写:
{ [K in keyof O]: K extends 'opt1' ? true : O[K] }
语法O[K]
是索引访问,意思是“具有类型O
键的属性的类型K
”。
那么您的示例应该可以正常工作,(假设O
是Options<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!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句