Created
October 2, 2021 08:27
-
-
Save hyunbinseo/52cf0e53c43d0f06a3e3fc0a89114b75 to your computer and use it in GitHub Desktop.
Set object's value type while keeping key autocomplete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Types */ | |
type Person = { | |
age: number, | |
city: string | |
} | |
type People = { [name: string]: Person } | |
/* Method 1 */ | |
/* | |
* Autocomplete does not work | |
* | |
* According to the annotated type, people's key(=name) is any string | |
* Consult comments of https://stackoverflow.com/a/52157355/12817553 | |
*/ | |
const people: People = { | |
Adams: { age: 18, city: 'New York City' }, | |
Baker: { age: 19, city: 'Los Angeles' }, | |
Clark: { age: 20 } | |
// Error: Property 'city' is missing in type '{age: number}' but required in type 'Person' | |
}; | |
/* Method 2 */ | |
/* | |
* Autocomplete does work | |
* | |
* people.Adams | |
* people.Baker | |
* people.Clark | |
*/ | |
const person = (info: Person): Person => info; | |
const people = { | |
Adams: person({ age: 18, city: 'New York City' }), | |
Baker: person({ age: 19, city: 'Los Angeles' }), | |
Clark: person({ age: 20 }) | |
// Error: Property 'city' is missing in type '{age: number}' but required in type 'Person' | |
}; | |
// eslint-disable-next-line @typescript-eslint/no-unused-vars | |
const checkPeople: People = people; | |
// Error: Property 'city' is missing in type '{age: number}' but required in type 'Person' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment