簡體   English   中英

強制對象鍵的類型

[英]enforce type of Object's Key

我正在嘗試制作一個只能具有某些鍵的字典對象。

我想將鍵限制為type rate

type rate = 60 | 30 | 20 | 15 | 12 | 10 | 6 | 5 | 4 | 3 | 2 | 1;
//so i can do this
const d = {
  60 : 100, //fine
  20 : 150, //fine
  11 : 120, //<--- detect as not allowed
}

我嘗試了以下方法並努力檢測錯誤類型,例如11 ,但它強制 Object 擁有所有我不想要的鍵。

const d2 : Record<rate, number> = {
  60 : 100,
  20 : 150,
  11 : 120, //<--- not allowed
} //<--- error: Type is missing the properties 60, 30, 20, 15,...

我需要一種允許這樣做的類型:

const ej1 : T = {
  60 : 10,
  20 : 11,
}
const ej2 : T = {
  30 : 50,
  10 : 60,
  2  : 4,
}

而不是這個:

const ej3 : T = {
  10 : 170,
  11 : 150, //<--- invalid property
  14 : 120, //<--- invalid property
}

嘗試使用Partial使所有鍵可選:

type rate = 60 | 30 | 20 | 15 | 12 | 10 | 6 | 5 | 4 | 3 | 2 | 1;

const d2: Partial<Record<rate, number>> = {
  60: 100,
  20: 150,
}; // no error!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM