-
-
Save ypcode/65b94fa6f315a588a5ab6b2f1488f673 to your computer and use it in GitHub Desktop.
labelKeyResolverSample.ts
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
import * as strings from 'myStrings'; | |
const getLocalizedStringKey: (keyResolver: (() => string)) => string = (nameResolver: () => string) => { | |
console.log("getLocalizedStringKey() - name resolver: ", nameResolver); | |
const dotFormNamePattern = /function\s*\(\)\s*\{\s*return (.*)\.(.*)\s*\}/; | |
const dotFormNameMatch = dotFormNamePattern.exec(nameResolver + ''); | |
let labelKey: string = null; | |
if (dotFormNameMatch == null) { | |
const arrayIndexingFormNamePattern = /return (.*)\[\"(.*)\"\]/; | |
const arrayIndexingFormNameMatch = arrayIndexingFormNamePattern.exec(nameResolver + ''); | |
console.log("getLocalizedStringKey() - uses array indexing form"); | |
if (arrayIndexingFormNameMatch == null) { | |
throw new Error("The keyResolver is invalid. Make sure to use '() => strings.LabelKey'"); | |
} | |
labelKey = arrayIndexingFormNameMatch[2]; | |
} else { | |
console.log("getLocalizedStringKey() - uses dot form"); | |
labelKey = dotFormNameMatch[2]; | |
} | |
return labelKey; | |
}; | |
const getKey = (labelKey: string | (() => string)) => { | |
let key: string = null; | |
if (!labelKey) { | |
throw new Error('The labelKey argument is not set'); | |
} | |
if (typeof labelKey === 'string') { | |
key = labelKey as string; | |
} else if (typeof labelKey === 'function') { | |
key = getLocalizedStringKey(labelKey as (() => string)); | |
} else { | |
key = (labelKey as any).toString(); | |
} | |
return key; | |
}; | |
export const doStuff = (labelKey: string | (() => string)) => { | |
const effectiveKey = getKey(labelKey); | |
// Do stuff with key here ... | |
}; | |
// I can than use | |
doStuff(() => strings.MyKey); // <= Compilation will succeed | |
//doStuff(() => strings.MyKy); // <= Compilation would fail | |
// instead of | |
doStuff("MyKey"); // <= Compilation will succeed and code will work fine | |
doStuff("Myky"); // <= Compilation will succeed and code won't work as expected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment