Douglas C Vasconcelos
Douglas C Vasconcelos

Reputation: 589

How to reference the type of a property?

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

Upvotes: 3

Views: 216

Answers (1)

Mu-Tsun Tsai
Mu-Tsun Tsai

Reputation: 2534

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 };

Upvotes: 6

Related Questions