string[] 和 [string] 的区别 [英] Difference between string[] and [string]

查看:44
本文介绍了string[] 和 [string] 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 Typescript 示例.第一行导致错误类型未定义[] 不可分配给类型[字符串]".最后两行编译.

let giveAnError: [string] = [];让 isOK: string[] = [];let isAlsoOK: [string] = ["foo"];

你必须如何解释 Typescript 中的类型定义 [string]?

解决方案

第一个 (givesAnError) 和最后一个 (isAlsoOK) 是元组,第二个 (isOK) 是一个数组.>

对于数组,您的所有元素都属于同一类型:

let a: string[];让 b: 布尔 [];让 c: 任何 [];

但是对于元组,您可以有不同的类型(和固定长度):

let a: [string, boolean, number];让 b: [任何, 任何, 字符串];

所以:

a = ["str1", true, 4];//美好的b = [真, 3, "str"];//美好的

但是:

a = [4, true, 3];//不好,因为第一个元素不是字符串b = [真, 3];//不好,因为 b 只有两个元素而不是 3

了解 javascript 输出将始终使用数组很重要,因为 js 中没有元组这样的东西.
但是对于编译时间它很有用.

Consider the following Typescript example. The first line results in an error 'type undefined[] is not assignable to type [string]'. The last two lines do compile.

let givesAnError: [string] = [];
let isOK: string[] = [];
let isAlsoOK: [string] = ["foo"];

How do you have to interprete the type definition [string] in Typescript?

解决方案

The first (givesAnError) and last (isAlsoOK) are tuples, and the second (isOK) is an array.

With arrays all of your elements are of the same type:

let a: string[];
let b: boolean[];
let c: any[];

But with tuples you can have different types (and a fixed length):

let a: [string, boolean, number];
let b: [any, any, string];

So:

a = ["str1", true, 4]; // fine
b = [true, 3, "str"]; // fine

But:

a = [4, true, 3]; // not fine as the first element is not a string
b = [true, 3]; // not fine because b has only two elements instead of 3

It's important to understand the the javascript output will always use arrays, as there's no such thing as tuple in js.
But for the compilation time it is useful.

这篇关于string[] 和 [string] 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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