从联合类型中以特定类型返回属性的正确方式

huangapple go评论88阅读模式
英文:

Correct way to return a property as a specific type from a union type

问题

我需要从应用程序中的不同位置的函数中返回一个属性。该属性可以是两种类型中的一种,都具有字符串文字属性。其中一种是另一种的扩展。如何在类型保护中将传入的同一变量强制转换为其中一种类型或另一种类型?

type NameA = 'A' | 'B' | 'C';
type NameB = NameA | 'D' | 'E';
function nameTypeGuard(
    name: NameA | NameB
  ): NameA | NameB {
    if (some condition) {
      return name as NameA;
    } else {
      return name as NameB;
    }
  }
英文:

I have 1 property I need to return from a function in different places in an application.
This property could be 1 of 2 types, both have properties that are string literals. One is an extension of the other.
How can I return the same variable I am passing in cast as one type or the other in a type guard?

type NameA = 'A'| 'B' | 'C'
type NameB = NameA | 'D' | 'E'
function nameTypeGuard(
    name: NameA | NameB
  ):  NameA | NameB{
    if (some condition) {
      return name as NameA;
    } else {
      return name as NameB;
    }
  }

答案1

得分: 4

你可以使用条件类型作为返回类型。使用泛型,我的初始解决方案可能如下所示:

type NameA = 'A' | 'B' | 'C';
type NameB = 'A' | 'D' | 'E';

function nameTypeGuard<
  T extends NameA | NameB,
  R = T extends NameA ? NameA : NameB
>(
  name: T
): R {
  return name as unknown as R;
}

const a = nameTypeGuard("A");
const b = nameTypeGuard("B");
const c = nameTypeGuard("C");
const d = nameTypeGuard("D");
const e = nameTypeGuard("E");

TypeScript Playground: 链接

英文:

You can use a Conditional Type as the return type. Using Generics, my initial solution would look something like this:

type NameA = &#39;A&#39; | &#39;B&#39; | &#39;C&#39;;
type NameB = &#39;A&#39; | &#39;D&#39; | &#39;E&#39;;

function nameTypeGuard&lt;
  T extends NameA | NameB,
  R = T extends NameA ? NameA : NameB
&gt;(
  name: T
): R {
  return name as unknown as R;
}

const a = nameTypeGuard(&quot;A&quot;);
const b = nameTypeGuard(&quot;B&quot;);
const c = nameTypeGuard(&quot;C&quot;);
const d = nameTypeGuard(&quot;D&quot;);
const e = nameTypeGuard(&quot;E&quot;);

TypeScript Playground: Link

huangapple
  • 本文由 发表于 2023年7月27日 18:35:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定