首页 > 解决方案 > TypeScript const 断言和声明之间有什么区别?

问题描述

我刚刚阅读了constTypeScript 3.4 RC 中的新断言功能,但我没有看到它与使用const声明有何不同。

我使用公告页面中的一个示例对此进行了测试,该示例显然演示了 using as const( constassertion) 如何防止文字类型被扩大(例如,"circle"to string)。

// Example from official announcement
function getShapes() {
  let result = [
    { kind: "circle", radius: 100 },
    { kind: "square", sideLength: 50 },
  ] as const;

  return result;
}

for (const shape of getShapes()) {
  if (shape.kind === "circle") {
    console.log("Circle radius", shape.radius);
  } else {
    console.log("Square side length", shape.sideLength);
  }
}

// Output:
// Circle radius 100
// Square side length 50

但是,当我删除const断言并改用const声明时,编译器输出控制台输出没有任何变化,也没有引发错误。

// Altered getShapes function
function getShapes() {
  const result = [
    { kind: "circle", radius: 100 },
    { kind: "square", sideLength: 50 },
  ];

  return result;
}

那么有什么区别呢?公告页面列出了使用const断言的三个原因:

• 该表达式中的文字类型不应扩展(例如,不要从“hello”变为字符串)
• 对象文字获得只读属性
• 数组文字变为只读元组

但它没有解释断言和声明的不同之处。

标签: typescripttypescript3.0

解决方案


const声明是声明后不能更改的变量声明。这是 Typescript 支持的 Javascript 功能。

const x ={ n: 10} ;
x.n = 11; //ok
x= { n:11}; // error 

constassertion 是一种类型断言,它对断言目标具有您所描述的影响。

const x ={ n: 10} as const;
x. n = 11; // error n is readonly 

推荐阅读