Reputation: 5554
I would like to map a plain old Javascript type to an equivalent one using Knockout observables.
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>
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>
}
Upvotes: 1
Views: 126
Reputation: 327624
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!
Upvotes: 4