Skip to content

Instantly share code, notes, and snippets.

@dacre-denny
Created April 7, 2019 05:17
Show Gist options
  • Save dacre-denny/915097a99055e02b4556742292a8051d to your computer and use it in GitHub Desktop.
Save dacre-denny/915097a99055e02b4556742292a8051d to your computer and use it in GitHub Desktop.
TypeScript: Generic function that enforces typed value that corresponds to typed key
/* Enforces value type to correspond to that of key, in supplied map object */
function foo<T, K extends keyof T>(map:T, key:K, value: T[K]) {
map[key] = value;
}
interface Apple {
color:string;
weight:number;
}
propSetter({} as Apple, 'color', 'red') // Allowed, value type matches that of key
propSetter({} as Apple, 'weight', 'green') // Not allowed, weight key has type number
interface Car {
make:string;
model:string;
year:number;
}
propSetter({} as Car, 'make', 1) // Not allowed, make key has type string
propSetter({} as Car, 'year', 2019) // Allowed, year key has type number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment