Mattia
Mattia

Reputation: 2281

Typescript: Can a type be parameterized on its own keys?

I would like to create a type where the values are references to its own properties. Something along the lines of:

type T = {[k:string]: keyof *a reference to this type*}; // 

so that you could write something like this:

const t:T = {
  a:"b", // valid
  b:"a", // valid
  c:"d" // invalid since "d" is not a property of t
};

Is this possible without breaking the type up or explicitly specifying the properties up front?

Upvotes: 2

Views: 36

Answers (1)

jcalz
jcalz

Reputation: 328312

No concrete type T has such a definition, but you can represent your T as a generic constraint. That means instead of annotating like const t: T = ..., you'd want to use a generic helper function and call it like const t = asT(...). Like this:

const asT = <T extends Record<keyof T, keyof T>>(t: T) => t;

const t = asT({
  a: "b",
  b: "a",
  c: "d" // error! // "d" not assignable to "a"|"b"|"c"
});

This gives you the error exactly where you expect it. Okay, hope that helps; good luck!

Playground link to code

Upvotes: 1

Related Questions