![](/img/trans.png)
[英]Typescript inline object constructor with generics results in too broad type
[英]Is there a way for typescript to type using broad keys of a defined object in typescript?
const obj: {[key: string]: string} = {foo: 'x', bar: 'y'};
type ObjType = keyof typeof obj;
在不修改obj
的類型的情況下,如何讓ObjType
只接受“foo”或“bar”而不接受任何字符串?
這不能在 typescript 4.8 上完成。 您不能限制類型,並獲取該類型的更具體版本以在同一分配中使用。
典型的解決方法是使用通用的 function,這有點糟糕。
function makeObj<T extends { [key: string]: string }>(obj: T) {
return obj
}
const obj = makeObj({foo: 'x', bar: 'y'})
type ObjType = keyof typeof obj // 'foo' | 'bar'
但是,下一個版本的 typescript (4.9) 似乎可能包含satisfies
運算符。 請參閱此 github 問題
這將允許您應用約束,並一次推斷出更具體的類型。
const obj = {foo: 'x', bar: 'y'} satisfies { [key: string]: string }
type ObjType = keyof typeof obj // 'foo' | 'bar'
但無論哪種方式,您都必須修改obj
的聲明方式才能使這些工作正常進行。
讓推理完成工作:
const obj = {foo: 'x', bar: 'y'};
type ObjType = keyof typeof obj; // "foo" | "bar"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.