在 TypeScript 中定义具有多种类型的数组 [英] Defining array with multiple types in TypeScript

查看:132
本文介绍了在 TypeScript 中定义具有多种类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下形式的数组:[ 1, "message" ].

我将如何在 TypeScript 中定义它?

解决方案

在 TypeScript 中定义多类型数组

使用联合类型(string|number)[] 演示:

const foo: (string|number)[] = [ 1, message";];

<块引用>

我有一个如下形式的数组:[ 1, message";].

如果你确定总是只有两个元素 [number, string] 那么你可以将它声明为一个元组:

const foo: [number, string] = [ 1, message";];

重要提示

当您想访问仅在其中一种类型上可用的属性时,这不适用于具有不同属性的复杂类型.

查看这个较新的答案.

I have an array of the form: [ 1, "message" ].

How would I define this in TypeScript?

解决方案

Defining array with multiple types in TypeScript

Use a union type (string|number)[] demo:

const foo: (string|number)[] = [ 1, "message" ];

I have an array of the form: [ 1, "message" ].

If you are sure that there are always only two elements [number, string] then you can declare it as a tuple:

const foo: [number, string] = [ 1, "message" ];

IMPORTANT NOTE

This won't work with complex types with different properties, when you want to access a property available on only one of the types.

See this newer answer.

这篇关于在 TypeScript 中定义具有多种类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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