给出一个带有不同类型参数的函数,如何找出传递给该函数的类型?
示例
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
之类的每种类型编写一个自定义函数,这又会在我的上下文中导致大量开销。
在打字稿中解决此问题的适当方法是什么?
答案 0 :(得分: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
}