为什么在打字稿中``'nect const foo = 3`法律''



我正在尝试编写一些打字稿声明文件,然后发现声明const并为其分配值是合法的。

declare const foo = 1;        // This is legal
declare const bar = 'b';      // This is legal too
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.

在我的理解中,在声明语句中分配价值应该是非法的。

我在const语句中知道,foo的类型可以推断为1,但是,declare const foo: 1不是更好的声明吗?

为什么打字稿允许为declare const分配一个值?

我无法确定为什么是这样,但这是我的理解。我认为这在官方文档中没有明确描述,但这似乎对我来说是最有意义的。考虑到规格指出分配不可能,这似乎是编译器中的错误。

AmbientDeclaration:宣布环境Ambientvariabledeclaration:VAR AmbientBindingList;让AmbientBindingList;const AmbientBindingList;AmbientBindingList:环境AmbientBindingList,AmbientBinding环境:bindingIdentifier typeannotation_opt

当您 declare变量时,您只是向编译器说,应该假定该名称存在一些符号。实际实施将在其他地方提供。该声明实际上不会发出任何内容。

通常,当您使用declare时,您也会提供类型。在这种情况下,可以使用数字或字符串,因为它们既是文字,又有效的常数值,并且编译器可以推断符号应该是什么。否则您提供的价值没有其他效果。

我同意这很困惑,如果不允许该任务,这可能会更有意义。在环境环境中,您只提供有关应可用的符号和类型的信息。

至于为什么其他人不起作用:

  • BAZ-您正在尝试为声明分配一个非恒定价值
  • foo1,bar1-您正在尝试将非恒定值分配给非const变量
  • baz1-您正在宣布具有某些实现的函数(什么都不做)。要声明函数,您必须使用没有正体的函数语法,一个"原型"

    declare function baz(): void; // function baz returns void
    

首先,关于https://www.typescriptlang.org/docs/handbook/declaration/declaration-merging.html

其次:1定义了foo的类型,而不是foo的值,因此您不能使用它,因为它要指出foo只能是1,但不能将1分配给foo。

希望此帮助

最新更新