As I was working on creating a TypeScript declaration file, I discovered that it is permissible to declare a constant and assign a value to it.
declare const foo = 1; // This is considered valid
declare const bar = 'b'; // This is also acceptable
declare const baz = () => {}; // ERROR: A 'const' initializer in an ambient context must be a string or numeric literal.
declare var foo1 = 1; // ERROR: Initializers are not allowed in ambient contexts.
declare let bar1 = 2; // ERROR: Initializers are not allowed in ambient contexts.
declare function baz1() {} // ERROR: An implementation cannot be declared in ambient contexts.
In my opinion, it seems questionable to allow assigning a value in a declare statement.
I understand that in the const statement, the type of foo
can be inferred as 1
. However, wouldn't declare const foo: 1
be a more appropriate declaration?
What could be the reason behind TypeScript permitting declare const
to have an assigned value?