1

I was wondering; is something like this possible ?

interface User {
  name: string;
  age: number;
}

// The syntax User['*'] doesn't exist, this is just an example
const user: User['*'] = 'Bob'; // No error
const user: User['*'] = 32; // No error
const user: User['*'] = true; // Error

I know about the "or" (|), but this can become really redondent if the User interface has a lot of typed properties.

Anatole Lucet
  • 1,603
  • 3
  • 24
  • 43

1 Answers1

2

You can use an indexed type query with keyof T to get a union of all possible values in an interface:

interface User {
   name: string;
   age: number;
}

const userValue1: User[keyof User] = 'Bob'; // No error
const userValue2: User[keyof User] = 32; // No error
const userValue3: User[keyof User] = true; // Error

If you use this a lot, a helper type might help:

type ValueOf<T> = T[keyof T]
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357