I have an object where all the keys are string, some of the values are string and the rest are objects in this form:
var object = { "fixedKey1": "something1", "fixedKey2": "something2", "unknownKey1": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'}, "unknownKey2": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'}, "unknownKey3": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'}, ... ... };
In this object fixedKey1
and fixedKey2
are the known keys which will be there in that object. unknownKey
- value pair can vary from 1-n.
I tried defining the interface of the object as:
interface IfcObject { [keys: string]: { param1: number[]; param2: string; param3: string; } }
But this throws the following error:
Variable of type number is not assignable of type object
Which I found out that it is not able to assign this interface to "fixedKey - value" pair.
So, how can I do the type checking of this kind of variables?
If you want to set the properties of an interface to have a default value of undefined , you can simply make the properties optional. Copied!
unknown is the type-safe counterpart of any . Anything is assignable to unknown , but unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.
In TypeScript, object is the type of all non-primitive values (primitive values are undefined , null , booleans, numbers, bigints, strings). With this type, we can't access any properties of a value.
TypeScript Interface TypeTypeScript allows you to specifically type an object using an interface that can be reused by multiple objects. To create an interface, use the interface keyword followed by the interface name and the typed object.
It's not exactly what you want, but you can use a union type:
interface IfcObject { fixedKey1: string fixedKey2: string [key: string]: string | { param1: number[]; param2: string; param3: string; } }
It covers your case. But the unknown properties could be of type string
.
export interface IfcObjectValues { param1: number[]; param2: string; param3: string; } interface MyInterface { fixedKey1: string, fixedKey2: number, [x: string]: IfcObjectValues, }
Your code in action, see here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With