gpt4 book ai didi

javascript - 确定在 typescript 中可能具有多种类型的参数类型

转载 作者:行者123 更新时间:2023-12-05 03:51:34 25 4
gpt4 key购买 nike

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

例子

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,这在我的上下文中会再次导致大量开销。

在 typescript 中处理这个问题的合适方法是什么?

最佳答案

基本上只有 2 个选项,如 this question 的接受答案中所述。 .

What you can do is check that the shape of an object is what you expect, and TypeScript can assert the type at compile time using a user-defined type guard that returns true (annotated return type is a "type predicate" of the form arg is T) if the shape matches your expectation:

For class types you can use JavaScript's instanceof to determine the class an instance comes from, and TypeScript will narrow the type in the type-checker automatically.

我自己的旁注:

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

interface A {
value: string
}

interface B {
value: number
}

interface C {
value: SomeCustomInterface
}

interface D {
value: OtherCustomInterface
}

可以

interface GenericInterface<T>{
value: T
}

关于javascript - 确定在 typescript 中可能具有多种类型的参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62813930/

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