typescript 从对象属性推断类型的泛型接口

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

我有一个接口I,目标是确保val的属性类型与fn的返回类型相同。
有问题的类型限制为stringnumber

interface I<T extends string | number> {
  val: T;
  fn: () => T;
}

const x1: I<string> = {
  val: "hello",
  fn: () => "world",
};

const x2: I<number> = {
  val: 3,
  fn: () => 4,
};

有没有可能不需要显式地设置T,而是通过推理来设置它?这样我就可以:

// accepted
const x1: I = {
  val: "hello",
  fn: () => "world",
};

// accepted
const x2: I = {
  val: 3,
  fn: () => 4,
};

// rejected
const x3: I = {
  val: "hello",
  fn: () => 4,
};

// rejected
const x4: I = {
  val: 3,
  fn: () => "world",
};
p5cysglq

p5cysglq1#

据我所知,TS不可能为你的例子推断出类型。但是,有一种方法可以使用helper函数来达到类似的效果:

function make<T extends string|number>(input: I<T>) {
  return input;
}

// accepted
const x1 = make({
  val: "hello",
  fn: () => "world",
});

// accepted
const x2 = make({
  val: 3,
  fn: () => 4,
});

// rejected
const x3 = make({
  val: "hello",
  fn: () => 4,
});

// rejected
const x4 = make({
  val: 3,
  fn: () => "world",
});

Playground链接

相关问题