Skip to content

Instantly share code, notes, and snippets.

@Jacknq
Created April 14, 2023 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jacknq/14cc2b9e1d67fb65428b1f8bb319c48c to your computer and use it in GitHub Desktop.
Save Jacknq/14cc2b9e1d67fb65428b1f8bb319c48c to your computer and use it in GitHub Desktop.
typesript
function isAvailable<Obj>(
obj: Obj,
key: string | number | symbol
): key is keyof Obj {
return key in obj;
}
function loadLanguage(collection: Languages, lang: string) {
if (isAvailable(collection, lang)) {
// lang is keyof Languages
collection[lang]; // access ok!
}
}
function selectElement(collection: AllowedElements, elem: string) {
if (isAvailable(collection, elem)) {
// elem is keyof AllowedElements
collection[elem]; // access ok
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment