简体   繁体   English

Typescript 中对象文字的更严格的返回类型

[英]Stricter return type for object literal in Typescript

In this code在这段代码中

const s = "myKey" as const;
const myF = () => ({
  [s]: 0,
});

the type of myF is function myF(): {[p: string]: number, myKey: number} myF的类型是function myF(): {[p: string]: number, myKey: number}

where return type is {[p: string]: number, myKey: number}其中返回类型是{[p: string]: number, myKey: number}

As you can see, unwanted [p: string]: number leaks here.如您所见,不需要的[p: string]: number在这里泄漏。

How do I make my return type an expected {myKey: number} without explicit type annotation?如何在没有显式类型注释的情况下使我的返回类型成为预期的 {myKey: number}?

I don't want to go into explicit annotation just yet since I got some types with a LOT of fields.我还不想进入显式注释,因为我得到了一些带有很多字段的类型。

This is the default behavior of TypeScript.这是 TypeScript 的默认行为。 It always evaluates computed property to string.它总是将计算属性评估为字符串。

You can write custom helper to create objects:您可以编写自定义助手来创建对象:

const s = "myKey";

const record = <Prop extends PropertyKey, Value>(prop: Prop, value: Value) => 
  ({ [prop]: value }) as Record<Prop, Value>

// const myF: () => Record<"myKey", number>
const myF = () => record(s, 42)

Playground 操场

You don't need to use as const您不需要as const

Be aware that this solution has a drawback.请注意,此解决方案有一个缺点。

const drawback = record<'myKey' & { hello?: 'world' }, 42>('myKey', 42).myKey // error

Hence, you better to avoid using explicit generics for this function因此,您最好避免为此函数使用显式泛型

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

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