Using TypeScript, I want to create a Dictionary type mapping a string to an object. I want the value of the string to be restricted as follows.
type Person = {
id: string;
name: string;
age: number;
}
type DictionaryOfPersonsNeedsFixing = {
[idShouldBeRestrictedToMatchPersonId: string]: Person;
}
let persons: DictionaryOfPersonsNeedsFixing = {
'1': {
id: '1',
name: 'John',
age: 31
},
'wrongId': {
id: '2',
name: 'Jim',
age: 37
}
}
In the code above, I want TypeScript to tell me wrongId is not an allowed key and that we can only use '2' as the key.
Or another way would be, TypeScript should tell me id: '2' is not allowed, and that id should be set to wrongId.
I have tried updating the Person type to restrict id as follows:
type Person<K = string> = {
id: K;
name: string;
age: number;
}
Now, I can create a Person whose id must be '2', using the following syntax:
let jim: Person<'2'> = {
id: '2',
name: 'Jim'
age: 37
}
Here, I'll get an error, if I try to set the id field to anything other than '2'.
Similarly, I am able to update the Dictionary object to restrict the set of keys to a predefined set as follows:
type DictionaryOfPersonsWithRestrictedIds = {
[id in '1' | '2' | '3']?: Person<id>;
}
With this, TypeScript tells me there is an error if Person.id does not match the dictionary key. E.g.
let personsWithIncorrectKey: DictionaryOfPersonsWithRestrictedIds = {
'1': {
id: '1',
name: 'John',
age: 31
},
'wrongId': { // I get a red squiggle for this whole object since wrongId is not an allowed key
id: '2',
name: 'Jim',
age: 37
}
}
let personsWithIncorrectKey: DictionaryOfPersonsWithRestrictedIds = {
'1': {
id: '1',
name: 'John',
age: 31
},
'2': {
id: '3', // I get a red squiggle under id, since '2' is expected.
name: 'Jim',
age: 37
}
}
I want to be able to do this for any id, not just a predefined list.
I want the Dictionary key to match (i.e. be consistent with) the Person id field for any possible id.
Is this possible using TypeScript Types/Interfaces without having to write my own validation functions?