Created
April 7, 2019 05:17
-
-
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
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
/* 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