繁体   English   中英

在 typescript 中声明 object 中的所有属性相同类型?

[英]declare all property in object the same type in typescript?

我知道我可以在 typescript 中声明 object 的类型:

interface PersonType {
    fname: string
    lname: string
}
const person: PersonType = {fname:"John", lname:"Doe"};

但是有没有办法声明所有属性都具有字符串类型? 我不想指定任何属性键和类型。

您可以使用Record<Keys,Type > 实用程序:

构造具有一组属性类型的类型Keys Type

const foo: Record<string, string> = { fname: "John", lname: "Doe" };

操场


Record是以下的别名:

type Record<K extends string | number | symbol, T> = { [P in K]: T; }

如果您仍然需要仅使用接口,则可以执行以下操作:

interface PersonType {
    [index: string]: string
}

const person: PersonType = {fname:"John", lname:"Doe"};

在这里你可以找到文档

暂无
暂无

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

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