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

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

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

问题

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

  1. type NameA = 'A' | 'B' | 'C';
  2. type NameB = NameA | 'D' | 'E';
  1. function nameTypeGuard(
  2. name: NameA | NameB
  3. ): NameA | NameB {
  4. if (some condition) {
  5. return name as NameA;
  6. } else {
  7. return name as NameB;
  8. }
  9. }
英文:

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?

  1. type NameA = 'A'| 'B' | 'C'
  2. type NameB = NameA | 'D' | 'E'
  1. function nameTypeGuard(
  2. name: NameA | NameB
  3. ): NameA | NameB{
  4. if (some condition) {
  5. return name as NameA;
  6. } else {
  7. return name as NameB;
  8. }
  9. }

答案1

得分: 4

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

  1. type NameA = 'A' | 'B' | 'C';
  2. type NameB = 'A' | 'D' | 'E';
  3. function nameTypeGuard<
  4. T extends NameA | NameB,
  5. R = T extends NameA ? NameA : NameB
  6. >(
  7. name: T
  8. ): R {
  9. return name as unknown as R;
  10. }
  11. const a = nameTypeGuard("A");
  12. const b = nameTypeGuard("B");
  13. const c = nameTypeGuard("C");
  14. const d = nameTypeGuard("D");
  15. 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:

  1. type NameA = &#39;A&#39; | &#39;B&#39; | &#39;C&#39;;
  2. type NameB = &#39;A&#39; | &#39;D&#39; | &#39;E&#39;;
  3. function nameTypeGuard&lt;
  4. T extends NameA | NameB,
  5. R = T extends NameA ? NameA : NameB
  6. &gt;(
  7. name: T
  8. ): R {
  9. return name as unknown as R;
  10. }
  11. const a = nameTypeGuard(&quot;A&quot;);
  12. const b = nameTypeGuard(&quot;B&quot;);
  13. const c = nameTypeGuard(&quot;C&quot;);
  14. const d = nameTypeGuard(&quot;D&quot;);
  15. 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:

确定