Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference the type of a property?

Tags:

typescript

I would like to create a type Projection<T> that describes an object whose properties can only be a number (0 or 1) or a Projection of the type of that attribute.

Example:

Given types:

interface Person {
  name: string;
  address: Address
}

interface Address {
  street: string;
  country: string;
}

The Projection<Person> would be:

const p: Projection<Person> = { // this is a Projection<Person>
  name: 1,
  address: { // this is a Projection<Address>
    street: 0,
    country: 1
  }
}

Is that possible at all in typescript? I am getting stuck in the recursive Projection part

export type Projection<T> = { [K in keyof T]?: number | Projection<???> };

Using number | Projection<any> works, but of course does not check if the fields declared belong to Address

like image 368
Douglas C Vasconcelos Avatar asked Jan 23 '26 22:01

Douglas C Vasconcelos


1 Answers

I believe what you're looking for is

type Projection<T> = { [K in keyof T]: number | Projection<T[K]> };

Also, if the fields in your original structure are always strings, you can make it more specific by writing:

type Projection<T> = { [K in keyof T]: T[K] extends string ? number : Projection<T[K]> };

And if the fields are not always string, you may try:

type Projection<T> = { [K in keyof T]: T[K] extends object ? Projection<T[K]> : number };
like image 73
Mu-Tsun Tsai Avatar answered Jan 25 '26 18:01

Mu-Tsun Tsai