我想使用映射型別定義以下型別的型別:
例子:
const k0: Keyed = {}; // ok, empty
const k1: Keyed = { year: 1, month: 2, week: 3 }; // ok
const k2: Keyed = { year: 1 }; // ok, partial
const k3: Keyed = { hour: 1 }; // wrong! hour is not in 'year' | 'month' | 'week'
const k4: Keyed = { year: undefined }; // wrong, I want a number, not an undefined
我嘗試了以下方法:
type Keyed = {
[key in 'year' | 'month' | 'week']: number;
};
但因const k2: Keyed = { year: 1 }錯誤而失敗Type '{ year: number; }' is missing the following properties from type 'Keyed': month, week
然后我嘗試使用以下方法來允許沒有每個鍵的鍵控變數
type Keyed = {
[key in 'year' | 'month' | 'week']?: number;
};
但是接下來const d: Keyed = { year: undefined };就報 ok 了,所有對應的 'xxx may be undefined' 訊息
我想定義 的鍵Keyed必須是 之一'year' | 'month' | 'week',而不必定義所有屬性,并且值應該是數字(不是 null 也不是未定義)。
這似乎是一個非常簡單的案例,但我不喜歡實作它的方法。
我注意到顯式屬性也會出現類似的問題。如果我有:
type T = {
name?: string
}
所有這些都是有效的:
const t1: T = {name: 'sas'}
const t2: T = {name: undefined}
const t3: T = {}
我希望“名稱”屬性是可選的(也就是說,它可能會丟失),但如果它存在,我希望它是一個字串,而不是未定義的。
供參考:在 tsconfig.json 檔案中設定exactOptionalPropertyTypes選項的解決方案
uj5u.com熱心網友回復:
打開exactOptionalPropertyTypes你的tsconfig.json(你允許{}輸入,我認為沒關系)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407290.html
標籤:
