Skip to content

Instantly share code, notes, and snippets.

@lmcarreiro
Created November 18, 2017 14:24
Show Gist options
  • Select an option

  • Save lmcarreiro/3a2af88320025879317dce951bad0258 to your computer and use it in GitHub Desktop.

Select an option

Save lmcarreiro/3a2af88320025879317dce951bad0258 to your computer and use it in GitHub Desktop.
Convert SintaxKind marker name to the real kind name
export function getSyntaxKindName(kind: SyntaxKind): string
{
const markers: { [name: string]: string } = {
FirstAssignment : "EqualsToken",
LastAssignment : "CaretEqualsToken",
FirstCompoundAssignment : "PlusEqualsToken",
LastCompoundAssignment : "CaretEqualsToken",
FirstReservedWord : "BreakKeyword",
LastReservedWord : "WithKeyword",
FirstKeyword : "BreakKeyword",
LastKeyword : "OfKeyword",
FirstFutureReservedWord : "ImplementsKeyword",
LastFutureReservedWord : "YieldKeyword",
FirstTypeNode : "TypePredicate",
LastTypeNode : "LiteralType",
FirstPunctuation : "OpenBraceToken",
LastPunctuation : "CaretEqualsToken",
FirstToken : "Unknown",
LastToken : "LastKeyword",
FirstTriviaToken : "SingleLineCommentTrivia",
LastTriviaToken : "ConflictMarkerTrivia",
FirstLiteralToken : "NumericLiteral",
LastLiteralToken : "NoSubstitutionTemplateLiteral",
FirstTemplateToken : "NoSubstitutionTemplateLiteral",
LastTemplateToken : "TemplateTail",
FirstBinaryOperator : "LessThanToken",
LastBinaryOperator : "CaretEqualsToken",
FirstNode : "QualifiedName",
FirstJSDocNode : "JSDocTypeExpression",
LastJSDocNode : "JSDocPropertyTag",
FirstJSDocTagNode : "JSDocTag",
LastJSDocTagNode : "JSDocPropertyTag",
FirstContextualKeyword : "AbstractKeyword",
LastContextualKeyword : "OfKeyword",
}
const name = SyntaxKind[kind];
return markers.hasOwnProperty(name) ? markers[name] : name;
}
@tonyhallett
Copy link

This will not break in future versions. ( above is no longer valid )

function createEnumWithMarkerToString<T extends number = number>(enumeration: any){
  const map:Map<number, string> = new Map();
  for(let name in enumeration){
      const id = enumeration[name];
      if(typeof id === 'number' && !map.has(id)){
          map.set(id, name);
      }
  }
  return (value:T) => map.get(value) as string; //could be undefined if used the wrong enum member..
}

const syntaxKindToString = createEnumWithMarkerToString<SyntaxKind>(SyntaxKind);

const withKeywordIsAMarker = SyntaxKind.WithKeyword;

console.log(SyntaxKind[withKeywordIsAMarker]); // LastReservedWord
console.log(syntaxKindToString(withKeywordIsAMarker)); // WithKeyword
console.log(syntaxKindToString(SyntaxKind.LastReservedWord)) // WithKeyword

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment