【问题标题】:determine type of parameter that could have multiple types in typescript确定打字稿中可能有多种类型的参数类型
【发布时间】:2020-10-29 23:50:51
【问题描述】:

给定一个具有不同类型参数的函数,我如何找出传递给该函数的类型?

例子

interface SomeCustomInterface {
    title: string
}

interface OtherCustomInterface {
    subtitle: string
}


interface A {
    value: string
}

interface B {
    value: number
}

interface C {
    value: SomeCustomInterface
}

interface D {
    value: OtherCustomInterface
}

function doSomething(parameter: A | B | C | D): string {
    switch(parameter.type) { 
        // I know the cases are not valid TS. What should I do instead?
        case A:
            return parameter.value
        case B:
            return parameter.value.toString()
        case C:
            return parameter.value.title
        case D:
            return parameter.value.subtitle
    }
}

我知道有类型保护,但我担心这些

  1. 他们需要能够唯一标识每种类型。我看到有些人添加了一个属性kindtype,它允许他们识别一个类型以便对它进行类型保护。不过,这对我来说似乎是很多开销和样板。

  2. 您需要为type is Atype is B 等每种类型编写自定义函数,这在我的上下文中又会导致大量开销。

在打字稿中处理这个问题的适当方法是什么?

【问题讨论】:

  • 比较类型就够了吗?即parameter.valuenumberstringobject。如果是这样,您总是可以使用typeof?
  • 也可能是不同类型的对象。我更新了我的问题
  • 我研究了这种可能性,但发现它会产生大量开销。所有属性都命名为value,所以即使我创建了4 个额外的isAisBisCisD 方法,我仍然需要检查value 中的isSomeCustomTypeisOtherCustomType并且有了这个级联要求,它会增加太多的开销来支持我的项目。
  • 为什么不检查参数的类型呢?你真的不需要为此访问它的成员。

标签: javascript typescript typeguards


【解决方案1】:

this question 接受的答案中描述的基本上只有 2 个选项。

您可以做的是检查对象的形状是否符合您的预期,TypeScript 可以在编译时使用返回 true 的用户定义类型保护来断言类型(带注释的返回类型是如果形状符合您的期望,则形式 arg 为 T):

对于类类型,您可以使用 JavaScript 的 instanceof 来确定实例来自哪个类,TypeScript 会自动缩小类型检查器中的类型。

我自己的旁注:

如果你有相同的属性名,你可以使用泛型重构你的代码,比如:

interface A {
    value: string
}

interface B {
    value: number
}

interface C {
    value: SomeCustomInterface
}

interface D {
    value: OtherCustomInterface
}

可以

interface GenericInterface<T>{
 value: T
}

【讨论】:

  • 使用类感觉比我好。它们带有开箱即用的类型检查,不依赖于形状,据我所知,它们只是运行时的普通 JS 对象。
猜你喜欢
  • 2020-10-23
  • 2022-12-07
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
相关资源
最近更新 更多