Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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?

like image 949
ABOS Avatar asked Sep 20 '25 22:09

ABOS


1 Answers

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

like image 86
Titian Cernicova-Dragomir Avatar answered Sep 22 '25 14:09

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!