繁体   English   中英

从 object 属性推断类型的通用接口

[英]Generic interface inferring type from object property

我有一个接口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",
};

据我所知,TS 不可能为您的示例推断类型。 但是,有一种方法可以使用助手 function 实现类似的效果:

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",
});

游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM