简体   繁体   English

TypeScript:从 object 推断的类型

[英]TypeScript: inferred type from object

Is it possible to automatically generate/infer a flexible type from an object literal?是否可以从 object 文字自动生成/推断灵活类型?

I have the following object:我有以下 object:

export const config = {
  name: 'foo',
  bar: true,
} as const;

I want to automatically generate a flexible type based on this.我想基于此自动生成一个灵活的类型。 Something which looks like:看起来像:

type Config = {
  name: string;
  bar: boolean;
}

I have tried type Config = typeof config , but this gives me a type where name must be 'foo' , etc. All properties are fixed to a single value.我试过type Config = typeof config ,但这给了我一个name必须是'foo'等的类型。所有属性都固定为一个值。

I have also tried the following, but got the same result我也尝试了以下方法,但得到了相同的结果

export type Config = {
  [K in keyof typeof config]: typeof config[K];
};

I could of course write a separate type def, but my actual use case is more complex than the above example.我当然可以写一个单独的类型 def,但我的实际用例比上面的例子更复杂。

Ok, turns out my second example works as long as as const is removed from the object literal used as the template.好的,只要从用作模板的 object 文字中删除as const ,我的第二个示例就可以工作。 The readonly attribute can be added to the interred type: readonly 属性可以添加到 interred 类型:

export const config = {
  name: 'foo',
  bar: true,
}; // No `as const`

export type Readonly<Config = {
  [K in keyof typeof config]: typeof config[K];
}>; // Make this type read-only

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

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