Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

typescript类型问题

type Arr = number[] | string[];
type Arr1 = Array<string | number>;

const arr: Arr = [];
arr.push('123');

image.png
image.png

请问,为何使用Arr1不报错,Arr报错?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

第一个类型表示这个数组要么全都是 number,要么全都是 string,二者不可交叉出现。

第二个类型表示这个数组每个元素要么是 number,要么是 string,二者可以交叉出现。

而你用第一种类型的时候:

const arr: Arr = [];

此时 arr 里到底应该必须只存 number 还是必须只 string 是未知的,所以后面你必须先断言才可以 push。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...