Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to enforce two types have same keys?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading