定义具有多种类型的数组

发布于 2025-01-20 22:36:35 字数 61 浏览 5 评论 0 原文

我有一个形式的数组: [1,“消息”]

如何在打字稿中定义此?

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

How would I define this in TypeScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

我很坚强 2025-01-27 22:36:35

在 TypeScript 中定义多种类型的数组

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

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

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

如果您确定始终只有两个元素[number, string],那么您可以将其声明为元组:

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

您甚至可以为元组成员提供有意义的名称,例如id和<代码>文本

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

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" ];

And you can even provide meaningful names for the tuple members e.g. id and text:

const foo: [id: number, text: string] = [ 1, "message" ];
梦幻之岛 2025-01-27 22:36:35

如果您将其视为元组(请参阅 语言规范),然后:

var t:[number, string] = [1, "message"]

interface NumberStringTuple extends Array<string|number>{0:number; 1:string}
var t:NumberStringTuple = [1, "message"];

If you're treating it as a tuple (see section 3.3.3 of the language spec), then:

var t:[number, string] = [1, "message"]

or

interface NumberStringTuple extends Array<string|number>{0:number; 1:string}
var t:NumberStringTuple = [1, "message"];
抚你发端 2025-01-27 22:36:35

我的TS棉布抱怨其他解决方案,因此对我有用的解决方案是:

item: Array<Type1 | Type2>

如果只有一种类型,则可以使用:

item: Type1[]

My TS lint was complaining about other solutions, so the solution that was working for me was:

item: Array<Type1 | Type2>

if there's only one type, it's fine to use:

item: Type1[]
糖粟与秋泊 2025-01-27 22:36:35

TypeScript 3.9+ 更新(2020 年 5 月 12 日)

现在,TypeScript 还支持命名元组。这极大地提高了代码的可理解性可维护性查看官方 TS 游乐场。


所以,现在而不是unnamed:

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

我们可以添加名称:

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

注意:您需要一次添加所有名称,不能省略某些名称,例如:

type tIncorrect = [id: number, string]; // INCORRECT, 2nd element has no name, compile-time error.
type tCorrect = [id: number, msg: string]; // CORRECT, all have a names.

提示:如果您不确定的数量最后一个元素,你可以这样写:

type t = [msg: string, ...indexes: number];// means first element is a message and there are unknown number of indexes.

TypeScript 4.x+ Variadic Tuple Types

对于 TS 4.x,最后一个示例必须更改为这个:

type t = [msg: string, ...indexes: number[]];// means first element is a message and there are unknown number of indexes.

类型 number 更改为 number[]

更多信息在这里: https:// /www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#variadic-tuple-types

TypeScript 3.9+ update (May 12, 2020)

Now, TypeScript also supports named tuples. This greatly increases the understandability and maintainability of the code. Check the official TS playground.


So, now instead of unnamed:

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

We can add names:

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

Note: you need to add all names at once, you can not omit some names, e.g:

type tIncorrect = [id: number, string]; // INCORRECT, 2nd element has no name, compile-time error.
type tCorrect = [id: number, msg: string]; // CORRECT, all have a names.

Tip: if you are not sure in the count of the last elements, you can write it like this:

type t = [msg: string, ...indexes: number];// means first element is a message and there are unknown number of indexes.

TypeScript 4.x+ Variadic Tuple Types

The last example has to be changed to this one for TS 4.x:

type t = [msg: string, ...indexes: number[]];// means first element is a message and there are unknown number of indexes.

The type number is changed to number[].

More info here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#variadic-tuple-types

尴尬癌患者 2025-01-27 22:36:35

我已经以以下格式解决了可以包含多种类型项目的数组。

数组&lt; itemType1 | itemType2 | itemType3&gt;

这与测试和键入后卫非常有用。

这种格式与测试或键入后卫无法正常工作:

(itemType1 | itemType2 | itemType2 | itemType3 | itemType3) /代码>

I've settled on the following format for typing arrays that can have items of multiple types.

Array<ItemType1 | ItemType2 | ItemType3>

This works well with testing and type guards. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

This format doesn't work well with testing or type guards:

(ItemType1 | ItemType2 | ItemType3)[]

jJeQQOZ5 2025-01-27 22:36:35

我正在使用这个版本:

exampleArr: Array<{ id: number, msg: string}> = [
   { id: 1, msg: 'message'},
   { id: 2, msg: 'message2'}
 ]

它与其他建议有点相似,但仍然很容易并且很好记。

Im using this version:

exampleArr: Array<{ id: number, msg: string}> = [
   { id: 1, msg: 'message'},
   { id: 2, msg: 'message2'}
 ]

It is a little bit similar to the other suggestions but still easy and quite good to remember.

朮生 2025-01-27 22:36:35

如果您有兴趣获取数字或字符串数​​组,则可以定义一个类型,该类型将采用以下任一数组:

type Tuple = Array<number | string>
const example: Tuple = [1, "message"]
const example2: Tuple = ["message", 1]

如果您期望特定顺序的数组(即数字和字符串)

type Tuple = [number, string]
const example: Tuple = [1, "message"]
const example2: Tuple = ["messsage", 1] // Type 'string' is not assignable to type 'number'.

If you are interested in getting an array of either numbers or strings, you could define a type that will take an array of either

type Tuple = Array<number | string>
const example: Tuple = [1, "message"]
const example2: Tuple = ["message", 1]

If you expect an array of a specific order (i.e. number and a string)

type Tuple = [number, string]
const example: Tuple = [1, "message"]
const example2: Tuple = ["messsage", 1] // Type 'string' is not assignable to type 'number'.
悸初 2025-01-27 22:36:35
const myarray:(TypeA | TypeB)[];

甚至更好地避免在多个位置进行更改,以防您需要添加其他类型,请创建类型

type MyMixedType = TypeA | TypeB;
const myarray: MyMixedType[];
const myarray:(TypeA | TypeB)[];

or even better to avoid changes in multiple place in case you need to add another type, create type

type MyMixedType = TypeA | TypeB;
const myarray: MyMixedType[];
一抹微笑 2025-01-27 22:36:35
[ 1, "message" ] as const ;

如果你执行“as const”,类型将是

type const = readonly [1, "message"]

好的,因为计算机可以进行精确的类型推断。

[ 1, "message" ] as const ;

if you do "as const" , type will be

type const = readonly [1, "message"]

It is good because of the exact type inference that computer can possible.

娜些时光,永不杰束 2025-01-27 22:36:35

如果处理一个对我有用的对象中具有多种值类型的数组。

 { [key: string]: number | string }[]

If dealing with an array with multiple value types in an object this worked for me.

 { [key: string]: number | string }[]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文