是否可以在TypeScript中引用self属性类型?

jtoj6r0c  于 2022-12-14  发布在  TypeScript
关注(0)|答案(1)|浏览(165)

我想做一些像下面的代码记录器。
是否可以将unknown类型更改为specific类型?

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)

就是1 | 2 | 3 | "a" | "b" | "c"

s3fp2yjn

s3fp2yjn1#

您可以使用条件类型来分发T属性的联合类型:

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

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

相关问题