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

0

Issue

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?

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

Answered By – Titian Cernicova-Dragomir

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More