打字稿中 type[] 和 [type] 的区别 [英] Difference between type[] and [type] in typescript
本文介绍了打字稿中 type[] 和 [type] 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有两个接口:
interface WithStringArray1 {
property: [string]
}
interface WithStringArray2 {
property: string[]
}
让我们声明一些这些类型的变量:
Lets declare some variables of these types:
let type1:WithStringArray1 = {
property: []
}
let type2:WithStringArray2 = {
property: []
}
第一次初始化失败:
TS2322: Type '{ property: undefined[]; }' is not assignable to type 'WithStringArray1'.
Types of property 'property' are incompatible.
Type 'undefined[]' is not assignable to type '[string]'.
Property '0' is missing in type 'undefined[]'.
第二个没问题.
[string]
和 string[]
有什么区别?
推荐答案
[string]
表示字符串类型的Tuple
string[]
表示字符串数组[string]
denotes aTuple
of type stringstring[]
denotes an array of strings
在您的情况下元组的正确用法是:
The correct usage of the Tuple in your case would be:
let type2:WithStringArray2 = {
property: ['someString']
};
请参阅文档
这篇关于打字稿中 type[] 和 [type] 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文