![](/img/trans.png)
[英]From a static dictionary of strings, infer a type/interface describing the dictionary precisely, using string literals for value types
[英]Create new key value type from string literals types
我正在尋找一種基於字符串文字類型的值創建新 object 類型的方法。 我想提取每個字符串文字值並將其用作新創建類型中的鍵。 到目前為止,我陷入了這樣的解決方案:
export type ExtractRouteParams<T> = string extends T
? Record<string, string>
: { [k in T] : string | number }
type P = ExtractRouteParams<'Id1' | 'Id2'>
它符合我的預期。 P 有以下類型
type P = {
Id1: string | number;
Id2: string | number;
}
但不幸的是它拋出了一個錯誤
類型 'T' 不能分配給類型 'string | 號碼 | 象征'。 類型“T”不能分配給類型“符號”。
解決方案是基於那個操場完成的
使用內置PropertyKey
類型作為T
的通用約束:
// v-----------------v add here
export type ExtractRouteParams<T extends PropertyKey> = string extends T
? Record<string, string>
: { [k in T] : string | number }
type P = ExtractRouteParams<'Id1' | 'Id2'>
注意: PropertyKey
只是string | number | symbol
的別名。 string | number | symbol
string | number | symbol
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.