gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:32:33 24 4
gpt4 key购买 nike

在将泛型传入接口(interface)时,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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com