[英]Typescript - conditional mapped types
I would like to map a plain old Javascript type to an equivalent one using Knockout observables. 我想使用Knockout observables将普通的旧Javascript类型映射到等效类型。
interface KnockoutObservableArray<T> { }
interface KnockoutObservable<T> { }
class CustomerDto {
Name: string;
PetLicenseNumbers: number[];
}
// manually mapped to Knockout-equivalent
class CustomerDtoKo {
Name: KnockoutObservable<string>;
PetLicenseNumbers: KnockoutObservableArray<number>;
}
I'm trying to use mapped types to do the above automatically but I couldn't find a proper way to conditionally map arrays to KnockoutObservableArray<U>
while mapping the scalars to KnockoutObservable<U>
我正在尝试使用映射类型自动执行上述操作,但是在将标量映射到
KnockoutObservableArray<U>
时,我找不到合适的方法来有条件地将数组映射到KnockoutObservable<U>
type KnockoutType<T> = {
//[K in keyof T] : KnockoutObservableArray<T[K][0]>
[K in keyof T] : KnockoutObservable<T[K]>
}
type CustomerDtoKo2 = KnockoutType<CustomerDto>;
// gives
type CustomerDtoKo2 = {
Name: KnockoutObservable<string>,
PetLicenseNumbers: KnockoutObservable<number[]> // should be KnockoutObservableArray<number>
}
As you expect, conditional types will help you: 如您所料, 条件类型将帮助您:
type KnockoutType<T> = {
[K in keyof T]: T[K] extends Array<infer U> ?
KnockoutObservableArray<U> : KnockoutObservable<T[K]>
}
Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.