Home > Blockchain >  Is it possible to refer self property type in TypeScript?
Is it possible to refer self property type in TypeScript?

Time:12-13

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".

CodePudding user response:

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

  • Related