specify type of object's keys
See original GitHub issueI propose the generic object type Dictionary[Key, Value]
to define that all keys of an object should be of type Key
and all values should be of type Value
.
Example from #98
Type of
{
joe: {
skating: {time: 1000, money: 300},
cooking: {time: 9999, money: 999}
},
emily: {
running: {time: 300, money: 0}
}
}
can be described as
Dictionary[String, Dictionary[String, { time: Number, money: Number }]]
which can be splitted in smaller definitions using type aliases to provide more informative type names:
interface Name: String
interface Hobby: String
interface Expense {
time: Number, money: Number
}
interface ExpBy_Hobby: Dictionary[Hobby, Expense]
interface ExpBy_Hobby_Person: Dictionary[Name, ExpBy_Hobby]
Issue Analytics
- State:
- Created 7 years ago
- Reactions:4
- Comments:8 (1 by maintainers)
Top Results From Across the Web
Enforcing the type of the indexed members of a Typescript ...
Here, the interface AgeMap enforces keys as strings, and values as numbers. The keyword name can be any identifier and should be used...
Read more >Documentation - Keyof Type Operator
The keyof operator takes an object type and produces a string or numeric literal union of its keys. The following type P is...
Read more >TypeScript: Improving Object.keys - fettblog.eu
We have an object of type Person , with Object.keys we want to get all keys as strings, then use this to access...
Read more >How to use the keyof operator in TypeScript
The TypeScript handbook documentation says: The keyof operator takes an object type and produces a string or numeric literal union of its keys....
Read more >Create a Type from an object's Keys in TypeScript
Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person . The keyof...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
TypeScript calls it indexable types and uses this syntax
which looks similar to computed property names in object literals.
I think the nesting doesn’t hurt the readability. Since we kept the keyword
interface
in place oftype
to help the developers familiar with typescript transition easily, we could also adopt this syntax if it meets all of our requirements.The only additions that I would introduce are:
I am probably gonna do a PR that addresses all of these issues at once which would hopefully close #97, #98 and #99 if there’s an agreement.