简体   繁体   English

有没有办法让 typescript 使用 typescript 中定义的 object 的宽键来键入?

[英]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;

Without modifying the type of obj , how can I make ObjType accept only "foo" or "bar" and not any string?在不修改obj的类型的情况下,如何让ObjType只接受“foo”或“bar”而不接受任何字符串?

This can't be done on typescript 4.8.这不能在 typescript 4.8 上完成。 You cannot constrain a type, and get a more specific version of that type to use in the same assignment.您不能限制类型,并获取该类型的更具体版本以在同一分配中使用。

The typical workaround is to use a generic function, which sort of sucks.典型的解决方法是使用通用的 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'

See playground 看游乐场


However, the next version of typescript (4.9) seems likely to contain the satisfies operator.但是,下一个版本的 typescript (4.9) 似乎可能包含satisfies运算符。 See this github issue请参阅此 github 问题

This will let you apply a constraint, and infer the more specific type all at once.这将允许您应用约束,并一次推断出更具体的类型。

const obj = {foo: 'x', bar: 'y'} satisfies { [key: string]: string }

type ObjType = keyof typeof obj // 'foo' | 'bar'

See playground 看游乐场


But either way, you will have to modify how obj is declared to make any of this work.但无论哪种方式,您都必须修改obj的声明方式才能使这些工作正常进行。

Just let the inference do the job:让推理完成工作:

const obj = {foo: 'x', bar: 'y'};

type ObjType = keyof typeof obj; //  "foo" | "bar" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM