我有一个场景,我希望有多个类型/接口都在同一结构中:
type Base = {
type: 'x' | 'y' | 'z'
data: Record<string,string>
}
现在,我想创建类型;实现";这种基本类型,而它们中的每一个都以不同的方式缩小了这种类型:
type MyTypeX = {
type: 'x'
data: {
specificKey: string
}
}
type MyTypeY = {
type: 'y'
data: {
otherKey: string
}
}
但我找不到任何好办法。我知道我可以在没有基类型的情况下使用这些类型,但我想确保它们中的任何一个都有一个";类型";以及";数据";财产,并且每个财产都有一个合法类型。这就像对其他类型进行类型安全验证一样。有什么好办法吗?这在TS中可能吗?
也许您可以使用泛型类型Base
。类似以下内容:
type Type = 'x' | 'y' | 'z';
type Base<T extends Type, D extends Record<string, string>> = {
type: T;
data: D;
};
type Foo = Base<'x', { specificKey: string }>;
type Bar = Base<'y', { otherKey: string }>;
const foo: Foo = { type: 'x', data: { specificKey: 'foo' }};
const bar: Bar = { type: 'y', data: { otherKey: 'bar' }};
游乐场链接
如果可以使用接口,可以使用extends
关键字,如:
interface MyTypeX extends Base {
type: 'x'
data: {
specificKey: string
}
}
如果你做了一些与Base不兼容的东西(例如,你试图做type: boolean
(,typescript会在你定义MyTypeX时出错,MyTypeX错误地扩展了Base。
如果你需要使用类型而不是接口,你可以将你的类型和基类型进行交集。如果MyTypeX与基类型不兼容,则MyTypeX将为never
。定义类型时不会出现错误,但如果尝试使用类型,则会出现错误。
type MyTypeX = Base & {
type: 'x'
data: {
specificKey: string
}
}
游乐场链接