I have a relatively trivial question, say I need to create a new type from a JSON Response
My JSON response (lets call it Label Response) is as follows
{
id1: "someString"
someField: "someString"
someMoreFields: "someString"
EvenMorefields: "someString"
EvenMoreMoreFields: "someString"
SoManyManyFields: "someString"
EndlessFields: "someString"
}
Now if I choose to create a type from this response it would be as follows (correct me if i am wrong)
export type LabelResponse =
{
Fields: string;
FieldsMore:string;
MoreMoreFields:string;
MoreMoreMoreFields:string;
}
This is very verbose Since the more IDs, I have the more fields I will need and all the Ids are of the same type.
Is there a way to possible write this in short hand, for example, in my function parameter, instead of declaring a type for it
For example instead of
function myFunction(label:LabelResponse)
Would it be possible to declare my type in the parameter brackets ? Like this:
function myFunction(label:DeclareMyTypeHereSomehow?)
You can shorten the type definition using template literal types like following:
export type LabelResponse = { [K in `id${1|2|3|4}`]: string; }
This will give a type as:
type LabelResponse = {
id1: string;
id2: string;
id3: string;
id4: string;
}
Or if you don't care about the actual range, you can use id${number}:
export type LabelResponse = { [K in `id${number}`]: string; }
// errors since key doesn't start with id
const x: LabelResponse = {
'x1': 'hello'
}
// works
const y: LabelResponse = {
'id2': 'world'
}
// not works since it expects a number after id
const z: LabelResponse = {
'idx': '!'
}
If you don't care about the key at all, then you can just do:
type LabelResponse = {
[K: string]: string
}