typescript - 基于可选通用的接口(interface)中的强制键

标签 typescript typescript-typings typescript-generics

Typescript 中有没有办法让接口(interface)在传递泛型时具有强制键?

我正在寻找一种方法,仅当将泛型传递给接口(interface)时才能够为接口(interface)中的键定义类型。

例如。

interface IExample {
  foo: string
}
​
/* You can't declare 2 interfaces of the same name, but this shows the structure I am aiming for */
interface IExample<T> {
  foo: string,
  bar: T
}
​
/* Allowed */
const withoutBar: IExample {
  foo: 'some string'
}
​
/* Not allowed, as I've passed in a generic for Bar */
const withoutBar: IExample<number> {
  foo: 'some string'
}
​
/* Allowed */
const withBar: IExample<number> {
  foo: 'some string',
  bar: 1
};
​
/* Not allowed as I have not passed in a generic for Bar */
const withBar: IExample {
  foo: 'some string',
  bar: 1 // Should error on "bar" as I have not passed in a generic
};

最佳答案

您可以使用条件类型的类型别名。

type IExample<T = void> = T extends void ?  {
  foo: string
} : {
  foo: string,
  bar: T
}
​​
/* Allowed */
const withoutBar: IExample = {
  foo: 'some string'
}
​
/* Not allowed, as I've passed in a generic for Bar */
const withoutBar: IExample<number> = {
  foo: 'some string'
}
​
/* Allowed */
const withBar: IExample<number> = {
  foo: 'some string',
  bar: 1
};
​
/* Not allowed as I have not passed in a generic for Bar */
const withBar: IExample = {
  foo: 'some string',
  bar: 1 // Should error on "bar" as I have not passed in a generic
};

Playground

关于typescript - 基于可选通用的接口(interface)中的强制键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57286582/

相关文章:

typescript - 将泛型类型作为类型参数传递

typescript - 如何从联合创建类型数组类型

typescript - 将对象转换为 KV 值数组

通用的 typescript 两层联合类型推断

javascript - 错误 TS2554,预期参数 2 但得到 1

angular - NgxCharts 根据数据变化调整大小

node.js - 在 Webpack 中,如何动态设置公共(public)路径?

javascript - .d.ts 文件的构造和应用的简单示例?

TypeScript 无法使用 keyof 泛型参数作为对象的键

angular2自定义表单输入无法读取未定义的属性 'name'