在类方法内声明变量和对象时,为什么只有原始类型需要使用'let'?

问题描述 投票:0回答:1

以下示例

export class AppComponent implements OnInit {
  driveTypes: string[];
  vehicleTypes: string[];
  vehicle: Vehicle;
  test2:string;
  testObj2 :{key2:'value2'};

  method1(){
    let test1:string;
    let test2 = 'abc';
    test3:string; // 'string' only refers to a type, but is being used as a value here.(2693)
    test4 = 'def';  // Cannot find name 'test4'. Did you mean 'test1'?(2552)
    testObj : {key1:'value1'};
    let testObj2 : {key3:'value3'};
  }

method1()里面,为什么test3,test4有错误,必须使用let关键字like

let test1:string;
let test2 = 'abc';

但是

 testObj : {key1:'value1'};

没有任何错误吗?

angular typescript
1个回答
0
投票

您并没有真正比较相同的事物。你混合了声明和赋值

test4 = 'def';
错误,因为它之前没有声明为变量(let、const、var),并且您试图将值分配给不存在的东西。

testObj : {key1:'value1'};
Typescript 不会将其识别为变量声明,而是将其识别为“类型声明”。您定义了形状,但没有为其创建值。

如果您尝试像

a = { key1: 'value1' };
那样声明变量,您将遇到相同的错误。

但是,这一行 (

testObj : {key1:'value1'};
) 也不完整,因为您实际上并未声明变量,而只是指定其形状。如果稍后尝试使用 testObj,TypeScript 将抛出错误,因为变量本身不存在于内存中。

© www.soinside.com 2019 - 2024. All rights reserved.