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

Time:12-22

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?

CodePudding user response:

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

  • Related