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