gpt4 book ai didi

所有派生接口(interface)的 TypeScript 类型

转载 作者:行者123 更新时间:2023-12-02 18:14:15 24 4
gpt4 key购买 nike

我有一个像这样的接口(interface)继承层次结构:

interface IBase { type: stirng; }
interface IDerived1 extends IBase { type: "Derived1"; }
interface IDerived2 extends IBase { type: "Derived2"; }
...

这些实际上是为 C# 类型生成的接口(interface),这就是它们上的 type 鉴别器属性的原因。

是否可以在 TypeScript 中为所有可能的 type 字符串文字值编写类型,
仅基于现有类型层次结构,
那么不用手动一一指定它们吗?

我想要这样的smg:

type AllTypesOf<T extends {type: string}> = /* ? what comes here ? */;

...

const myVar: AllTypesOf<IBase>; // "Derived1" | "Derived2" | ...

我会这样使用:

function mySwitch(myArg: IBase) {
const type = myArg.type as AllTypesOf<IBase> // "Derived1" | "Derived2" | ...
switch(type) {
case "Derived1":
case "Derived2":
// ok

case "Derived3":
// NOK, error, does not exist such
}
}

最佳答案

TypeScript 遵循基本的继承规则: parent 对 child 一无所知。您可以对所有值进行枚举,然后在您的类型中引用它们:

enum AllTypesOf {
DERIVED_1 = "Derived1",
DERIVED_2 = "Derived2"
}

interface IBase { type: AllTypesOf }

interface IDerived1 extends IBase { type: AllTypesOf.DERIVED_1 }

function mySwitch(myArg: IBase) {
const type = myArg.type // Automatically typed as AllTypesOf
switch(type) {
case AllTypesOf.DERIVED_1:
case AllTypesOf.DERIVED_2:
// ok

case AllTypesOf.DERIVED_3: // error, does not exist in enum
// NOK, error, does not exist such
}
}

关于所有派生接口(interface)的 TypeScript 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71842495/

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