我有以下型別的代碼:
const myObject = {
foo: ['a'/span>, 'b'/span>, 'c'/span>]
}
type MyType = typeof myObject. foo extends [...infer Content] ? string : boolean
而且MyType的結果是型別string,正如預期的那樣。
但是如果我這樣修改代碼:
...
type MyType = typeof myObject. foo extends [infer First, ...infer Tail] ? ? string : boolean
MyType現在變成boolean。為什么?
為什么它在第一種情況下會擴展,而在第二種情況下不會?
uj5u.com熱心網友回復:
第一個用例:
const myObject = {
foo: ['a'/span>, 'b'/span>, 'c'/span>]
}
型別 MyType1 = string[] extends [...infer Content] ? string : boolean
[...infer Content] - 表示元組可能有0或1個或更多的元素。完全沒有限制。
因此,由于string[]是一個沒有明確長度的陣列(不是一個元組),你將得到string。
第二種情況
。
型別 MyType2 = string[] extends [infer First, ... infer Tail] ? ? string : boolean
[infer First, ...infer Tail] - 意思是你的元組應該至少有一個元素,因為First。
因為你正在檢查myObject.foo,它基本上是stirng[],TS不允許對string[]長度做任何假設。string[]是一個可改變的陣列。
嘗試讓myObject成為不可變的。
const myObject = {
foo: ['a'/span>, 'b'/span>, 'c'/span>]
} as const;
//span>字串
型別 MyType1 = typeof myObject. foo extends readonly [...infer Content] ? string : boolean
//string ?
型別 MyType2 = typeof myObject. foo extends readonly [infer First, ...infer Tail] ? ? string : boolean
現在,兩個MyType都是字串。
SUMMARY
['a', 'b', 'c']被推斷為string[],因為就像我說的,它是一個陣列而不是一個元組。
如果你想讓它成為一個元組,你可以使用['a', 'b', 'c'] 作為 const。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/322424.html
標籤:
上一篇:從矩陣中洗掉行
下一篇:用jq從陣列中提取所有欄位
