Background
Stuck with 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:
let myObj = {}
myObj[prop] = value
but we don't know the names of the properties in advance.
CodePudding user response:
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
andnumber
are your only two index signature options.)You can use the
Record
utility type, for exampleRecord<string, number>
which does much the same thing as the above:let myObj: Record<string, number> = {}; myObj[prop] = value;
You can use a
Map
instead of an 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.
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. :-) But that's inevitable if the property name is a runtime thing.