For example, I want the following two types - ViewModel and SaveModel to have same keys but different value types,
type User = {
id: number;
name: string;
age: number;
}
type Address = {
street: string;
zip: string;
}
type ViewModel = {
user: User;
address: Address;
}
type SaveModel = {
user: number;
address: string;
}
How to do this in typescript?
Since there does not seem to be any relationship between the types of the properties in ViewModel and the types of the properties in SaveModel you can create a type that constrains a second type to have the same keys:
type MustHaveKeys<V, S extends Record<keyof V, any>> = S;
type SaveModel = MustHaveKeys<ViewModel, {
user: number;
address: string;
}>
type SaveModelBad = MustHaveKeys<ViewModel, {
//user: number;
address: string;
}>
Playground Link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With