从联合类型接收单一类型的最佳实践是什么 [英] What is the best practice to receive a single type from an union type

查看:26
本文介绍了从联合类型接收单一类型的最佳实践是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种代码

interface MyInterface {
  name: string;
}

type MyType = string | MyInterface;

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  constructor() {
    console.log(this.getValueAsString('Hello World'));
    console.log(this.getValueAsString({name: 'Hello World'}));
  }

  // I want to return 'Hello World' for both possible types
  getValueAsString(myValue: MyType): string {
    // not working because compiler says name is no property of string
    // return myValue.name ? myValue.name : myValue;
  }
}

问题是,在我尝试的每种方式中,编译器总是出现,因为有些东西不适合这两种类型.

The problem is, that in each way I tried the compiler is always showing up because something does not fit for either of the types.

getValueAsString 的最佳解决方案是什么?

What would be the best solution for getValueAsString?

(stackblitz:https://stackblitz.com/edit/angular-jrty3q)

(stackblitz: https://stackblitz.com/edit/angular-jrty3q)

推荐答案

您使用 类型保护:

getValueAsString(myValue: MyType): string {
  return typeof myValue === "string" ? myValue : myValue.name;
}

在上面,由于 TypeScript 编译器知道 myValue 将是 stringMyInterfacetypeof myValue === "string" 守卫告诉它在条件的真部分(在 ? 之后),myValue 是一个字符串,而在假部分 (在 : 之后,它是 MyInterface.

In the above, since the TypeScript compiler knows that myValue will be either string or MyInterface, the typeof myValue === "string" guard tells it that in the true part of the conditional (after the ?), myValue is a string, and in the false part (after the :), it's MyInterface.

这篇关于从联合类型接收单一类型的最佳实践是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆