Names
FUNCTION
@skmtc/lang-typescript 0.19.1sanitizeIdentifier
Makes a name safe to emit as a JavaScript binding - export const <name>, class <name>, function <name>.
This is a different question from handleKey, which asks whether a name is safe as an object property. export is a perfectly good property key, so isIdentifierName('export') is true - but export const export = … is a syntax error. Reserved words therefore have to be checked separately, and against the module rules, where await, yield, let, static, eval and arguments are reserved too.
Two repairs, in order:
- Anything that is not a valid identifier name loses the offending characters, and gains a
_prefix if what remains still cannot start an identifier (a leading digit, a combining mark, or nothing at all). - A reserved word gains a
Valuesuffix - the convention already used byprotectedKeywordsfor property names (export→exportValue).
A name that is already safe is returned unchanged, so this is safe to apply unconditionally in a projection's toIdentifierName.
Two limits worth knowing:
- TypeScript type-alias names are not covered. TS additionally rejects its predefined type names there -
type string = numberis TS2457 - and those are not JavaScript reserved words, so they pass through. Generators emitting type aliases capitalise (Stringis a legal alias name), so this has no practical exposure today. - Sanitizing is lossy, so distinct names can collide. Schemas named
exportandexportValue, oruser-nameandusername, both arrive at one binding. The engine's definition-uniqueness check turns that into a hard error rather than a silent clobber.
Signature
import { sanitizeIdentifier } from '@skmtc/lang-typescript'
sanitizeIdentifier(name: string): stringParameters
name, string required
Example
sanitizeIdentifier('user') // 'user'
sanitizeIdentifier('Export') // 'Export' - capitalised, so not reserved
sanitizeIdentifier('export') // 'exportValue'
sanitizeIdentifier('await') // 'awaitValue'
sanitizeIdentifier('eval') // 'evalValue'
sanitizeIdentifier('2fa') // '_2fa'Returns
string