【发布时间】: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
}
}
我知道有类型保护,但我担心这些
-
他们需要能够唯一标识每种类型。我看到有些人添加了一个属性
kind或type,它允许他们识别一个类型以便对它进行类型保护。不过,这对我来说似乎是很多开销和样板。 -
您需要为
type is A或type is B等每种类型编写自定义函数,这在我的上下文中又会导致大量开销。
在打字稿中处理这个问题的适当方法是什么?
【问题讨论】:
-
比较类型就够了吗?即
parameter.value是number、string或object。如果是这样,您总是可以使用typeof? -
也可能是不同类型的对象。我更新了我的问题
-
我研究了这种可能性,但发现它会产生大量开销。所有属性都命名为
value,所以即使我创建了4 个额外的isA、isB、isC、isD方法,我仍然需要检查value中的isSomeCustomType和isOtherCustomType并且有了这个级联要求,它会增加太多的开销来支持我的项目。 -
为什么不检查参数的类型呢?你真的不需要为此访问它的成员。
标签: javascript typescript typeguards