js文件里面可以写ts代码吗?

作者站长头像
站长
· 阅读数 11
{(['left', 'right', 'top', 'bottom'] as const).map((anchor) => (
  <React.Fragment key={anchor}>
    <Button onClick={toggleDrawer(anchor, true)}>{anchor}</Button>
    <SwipeableDrawer
      anchor={anchor}
      open={state[anchor]}
      onClose={toggleDrawer(anchor, false)}
      onOpen={toggleDrawer(anchor, true)}
    >
      {list(anchor)}
    </SwipeableDrawer>
  </React.Fragment>
))}

以上的代码是material ui的一个js示例,请看第一行,无意中发现竟然有一个as const,这个代码是ts代码吗? js里面有这种表达式吗? 是啥意思阿,请大佬帮忙解答,肥肠感谢。

回复
1个回答
avatar
test
2024-07-11

这是 TypeScript 的 const 断言功能。

const 断言用于告诉 ts 编译器在为表达式推断类型时使用最具体的类型。如果不使用 const 断言的话,编译器会采用默认的行为,可能会使用更宽泛的类型。

例如:

const args = [8, 5];
// const args: number[]
const angle = Math.atan2(...args); // error! Expected 2 arguments, but got 0 or more.
console.log(angle);

上述 TypeScript 代码在执行时会报错,编译器在看到 const args = [8, 5]; 时会推测它的类型是 number[],此时编译器不知道这个数组有多少个元素。这种行为在大部分情况下是没问题的,因为我们通常对数组的操作是追加,删除元素等等。

不过代码执行到 Math.atan2(...args) 时就会报错,因为 Math.atan2 函数期望传入两个数字。但是编译器只知道 args 的类型是一个数字组成的数组,而并不记得数字的个数,这就导致了在编译时报错。

使用了 as const 之后:

const args = [8, 5] as const;
// const args: readonly [8, 5]
const angle = Math.atan2(...args); // okay
console.log(angle);

此时编译器得知 args 的类型是 readonly [8, 5],这是一个 readonly 元组类型。它的值是数字 85args 的长度是 2。一切都满足了要求,所以编译通过。

注意 TypeScript 不会在最终生成的 JavaScript 代码中包含 const 断言。它的目的只是用来告诉编译器代码的意图,从而方便编译器更准确的区分是正确的代码还是 bug。

JavaScript 里暂时没有 as const 语法,只有 const 关键字用于定义常量。

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容