[英]How to define an empty object in typescript
Background背景
Stuck with typescript.卡在 typescript 上。 I understand this declarations:
我理解这个声明:
let varName:number; //null,string,..declare simple variables.
let arrName:string[] // or arrName:number[]. etc
Apparently this is used for objects:显然这是用于对象:
//knowing type of the property
let obj: {property:string, also:number[]} = {property:'hello', also:[1,2,3]}
//now knowing the type of the property
let obj: {property:any, also:any[]} = {property: a && b || c, also:[1,'string', 'etc']}
But what happens when we don't know the names of the properties in advance?但是当我们事先不知道属性的名称时会发生什么?
Particularly, I am trying to translate this JS bit:特别是,我正在尝试翻译这个 JS 位:
let myObj = {}
myObj[prop] = value
but we don't know the names of the properties in advance.但我们事先并不知道属性的名称。
You have a few options:你有几个选择:
You can use an index signature type that allows any string or any number, for instance:您可以使用允许任何字符串或任何数字的索引签名类型,例如:
let myObj: {[key: string]: number} = {}; myObj[prop] = value;
...allows any string property name, with the values expected to be numbers. ...允许任何字符串属性名称,其值应为数字。 (Or you can use
{[key: number]: number}
to make the keys numbers. string
and number
are your only two index signature options.) (或者您可以使用
{[key: number]: number}
使键为数字。 string
和number
是您仅有的两个索引签名选项。)
You can use the Record
utility type , for example Record<string, number>
which does much the same thing as the above:您可以使用
Record
实用程序 type ,例如Record<string, number>
,它的作用与上述相同:
let myObj: Record<string, number> = {}; myObj[prop] = value;
You can use a Map
instead of an object:您可以使用
Map
代替 object:
let myObj: Map<string, number> = new Map(); myObj.set(prop, value);
In all three of those, number
as the value type is just an example, it can be any type you want (including a union type ), or unknown
if you won't know the type, or any
if you want to allow any type.在所有这三个中,作为值类型的
number
只是一个示例,它可以是您想要的任何类型(包括联合类型),或者如果您不unknown
类型,或者如果您想允许any
类型,则为任何类型.
It may be obvious, but I'll say it anyway: This does mean TypeScript can't help you with using the wrong property name on the object.这可能很明显,但我还是要说:这确实意味着 TypeScript 无法帮助您在 object 上使用错误的属性名称。 :-) But that's inevitable if the property name is a runtime thing.
:-) 但如果属性名称是运行时的东西,这是不可避免的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.