![](/img/trans.png)
[英]Typescript - How to assign Partial type to the property of same type of another 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.