Skip to content

Instantly share code, notes, and snippets.

@jonathonherbert
Last active May 5, 2021 13:53
Show Gist options
  • Save jonathonherbert/94d012477b335caa1bc3ae357f17f000 to your computer and use it in GitHub Desktop.
Save jonathonherbert/94d012477b335caa1bc3ae357f17f000 to your computer and use it in GitHub Desktop.
Typing key/value pairs generically in function signatures in Typescript
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