我想使用Knockout可观察对象将普通的旧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>;
}
我正在尝试使用映射类型自动执行上述操作,但我无法
找到适当的方法来有条件地将数组映射到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>
}
答案 0 :(得分:3)
如您所料,conditional types将为您提供帮助:
type KnockoutType<T> = {
[K in keyof T]: T[K] extends Array<infer U> ?
KnockoutObservableArray<U> : KnockoutObservable<T[K]>
}
祝你好运!