Typescript 基于可选泛型的强制键入接口

Typescript 基于可选泛型的强制键入接口,typescript,typescript-typings,typescript-generics,Typescript,Typescript Typings,Typescript Generics,在Typescript中有没有一种方法可以使一个接口在传入泛型时具有一个强制键 我正在寻找一种方法,只有在将泛型传递到接口中时,才能为接口中的键定义类型 例如 接口示例{ foo:string } ​ /*您不能声明两个同名的接口,但这显示了我想要的结构*/ 接口示例{ 傅:字符串, 酒吧:T } ​ /*允许*/ 不带BAR的常量:例如{ 傅:“一些字符串” } ​ /*不允许,因为我已经通过了一个通用的for Bar*/ 不带BAR的常量:例如{ 傅:“一些字符串” } ​ /*允许*/ 带

在Typescript中有没有一种方法可以使一个接口在传入泛型时具有一个强制键

我正在寻找一种方法,只有在将泛型传递到接口中时,才能为接口中的键定义类型

例如

接口示例{
foo:string
}
​
/*您不能声明两个同名的接口,但这显示了我想要的结构*/
接口示例{
傅:字符串,
酒吧:T
}
​
/*允许*/
不带BAR的常量:例如{
傅:“一些字符串”
}
​
/*不允许,因为我已经通过了一个通用的for Bar*/
不带BAR的常量:例如{
傅:“一些字符串”
}
​
/*允许*/
带bar的常量:例如{
foo:'一些字符串',
酒吧:1
};
​
/*不允许,因为我没有通过通用for Bar*/
带bar的常量:例如{
foo:'一些字符串',
bar:1//应该在“bar”上出错,因为我没有传入泛型
};

您可以使用条件类型创建类型别名

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
};
type IExample=T扩展了void?{
foo:string
} : {
傅:字符串,
酒吧:T
}
​​
/*允许*/
无栏常量:IExample={
傅:“一些字符串”
}
​
/*不允许,因为我已经通过了一个通用的for Bar*/
无栏常量:IExample={
傅:“一些字符串”
}
​
/*允许*/
带条形图的常数:IExample={
foo:'一些字符串',
酒吧:1
};
​
/*不允许,因为我没有通过通用for Bar*/
带条形图的常数:IExample={
foo:'一些字符串',
bar:1//应该在“bar”上出错,因为我没有传入泛型
};

工作正常!我需要练习条件类型。谢谢
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
};