Skip to main content

Command Palette

Search for a command to run...

TIL about typescript typing `as const`

Updated
1 min read
TIL about typescript typing `as const`

I knew that typescript supports a type being a specific string, rather than the string type, so (for example) a function parameter can only receive the string “foo” and not a different string. Today I learnt that this can be done by using the as const syntax.

class Foo {
  // prop1 is typed as string
  static prop1 = 'foo';

  // prop2 is typed as 'foo'
  static prop2 = 'foo' as const;

  static func1 = (input: typeof Foo.prop1) => console.log(`Input was ${input}`);
  static func2 = (input: typeof Foo.prop2) => console.log(`Input was ${input}`);
}

Foo.func1('bob'); // works fine
Foo.func2('bob'); // Argument of type '"bob"' is not assignable to parameter of type '"foo"'.

However, calling typeof will still return 'string' rather than 'foo'. That’s because using as const only affects how typescript checks types, not the javascript output which is produced from the typescript source code.