Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript const and const with as const

To the best of my understanding TypeScript views a const string variable as an immutable typed variable with only that value and no other possible value. I always thought that adding as const to that was redundant.

Why am I getting the following in the 2nd part of the example?

Argument of type 'string' is not assignable to parameter of type...

Example:

declare function each<T extends [any] | any[]>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T) => any, timeout?: number) => void;

const foo1 = 'FOO' as const;
const bar1 = 'BAR' as const;

declare function action1(value: typeof foo1 | typeof bar1): void;

each([
  [foo1],
])('test name', (value) => {
  // okay
  action1(value);
});

const foo2 = 'FOO';
const bar2 = 'BAR';

declare function action2(value: typeof foo2 | typeof bar2): void;

each([
  [foo2],
])('test name', (value) => {
  // Argument of type 'string' is not assignable to parameter of type '"FOO" | "BAR"'.(2345)
  action2(value);
});

Playground sample above is here.

like image 577
Guy Avatar asked Apr 30 '21 21:04

Guy


People also ask

What is as const TypeScript?

When using as const in TypeScript, we are able to set the properties of an object or the elements of an array to readonly , indicating to the language, that the type in the expression will not be widened (e.g. from 42 to number ).

Does TypeScript use const?

TypeScript follows the same rules as JavaScript for variable declarations. Variables can be declared using: var , let , and const .

Where is Tsbuildinfo?

tsbuildinfo doesn't exist, it'll be generated. But if it does, tsc will try to use that file to incrementally type-check and update our output files. These . tsbuildinfo files can be safely deleted and don't have any impact on our code at runtime - they're purely used to make compilations faster.

What is type assertion?

In Typescript, Type assertion is a technique that informs the compiler about the type of a variable. Type assertion is similar to typecasting but it doesn't reconstruct code. You can use type assertion to specify a value's type and tell the compiler not to deduce it.


1 Answers

Don't confuse const as a keyword for declaring immutable variables (same in JS by the way) with as const, which called const assertions.

Const assertions behaves slightly different depending on the type (see attached link to the documentation), but in case of literal types it basically means that it cannot be extended (or widened) to string. It narrows it to that specific literal type, which signals to compiler not to accept string and this is the exact error you are getting.

like image 174
Jenya Y. Avatar answered Sep 24 '22 17:09

Jenya Y.