简体   繁体   English

如何从 typescript 中的 object 文字声明类型?

[英]How to declare a type from an object literal in typescript?

I have an object:我有一个 object:

const foo = { bar: 123, baz: "lorem" };

I would like top obtain the type of this object automatically:我想自动获取这个 object 的类型:

type Foo = { bar: number, baz: string };

How can I do this?我怎样才能做到这一点?

You can use keyof and typeof to construct the Foo您可以使用keyoftypeof构造Foo

type Foo = { [P in keyof typeof foo]: typeof foo[P] }

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

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