Last active
May 5, 2021 13:53
-
-
Save jonathonherbert/94d012477b335caa1bc3ae357f17f000 to your computer and use it in GitHub Desktop.
Typing key/value pairs generically in function signatures in Typescript
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
type Fields = Record<string, number> | |
type Obj<ObjKey extends string, ObjVals extends Fields> = { [key in ObjKey]: ObjVals } | |
const obj = { "A": { fieldOne: 1 }, "B": { fieldTwo: 2 } } | |
const acceptsObj = <TKeys extends string, TFields extends Fields>(obj: Obj<TKeys, TFields>) => { | |
return <Key extends TKeys>(key: Key, fields: Obj<TKeys, TFields>[Key]) => undefined; | |
} | |
const fn = acceptsObj(obj) | |
// This is fine | |
fn("A", { fieldOne: 1 }) | |
// In the value, property 'fieldNope' does not exist | |
fn("A", { fieldNope: 1 }) | |
// In the keys, 'Nope' does not exist | |
fn("Nope", { fieldNope: 1 }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment