Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to refer self property type in TypeScript?

I want to make some logger like below code.

Is it possible to change unknown type to specific type?

type Poo = {
  prop1: 1 | 2 | 3;
  prop2: "a" | "b" | "c";
}

type Log<T> = {
  prop: keyof T;
  prev: unknown; // Todo
  cur: unknown; // Todo
}

const pooLogger: Log<Poo>[] = [];

const log: Log<Poo> = {
  prop: "prop1",
  prev: "a", // This line must cause error message like "a" is not 1 | 2 | 3
  cur: 1
}

pooLogger.push(log)

T[Log<T>["prop"]] is 1 | 2 | 3 | "a" | "b" | "c".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a conditional type to distribute the union type of T‘s properties:

type Log<T, P extends keyof T = keyof T> = P extends keyof T ?
  {prop: P; prev: T[P]; cur: unknown;} :
  never

Log<Poo> will be {prop: 'prop1', prev: 1|2|3} | {prop: 'prop2', prev: 'a'|'b'|'c'}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading