use*_*034 1 javascript typescript reactjs typescript-typings
I'm trying to learn Typescript with React, but this error got in my way. I don't understand why is it even happening. Here it is. Creating an array of strings that looks like colors array down there. I want to create types based on values of that array ("white" | "red" | "blue").
const colors = ["white", "red", "blue"] as const;
type Colors= typeof colors[number];
Run Code Online (Sandbox Code Playgroud)
If I do it like this, it works, Colors has wanted types
const colorsArr = ["white", "red", "blue"];
const colors = colorsArr as const
type Colors = typeof colors[number]
Run Code Online (Sandbox Code Playgroud)
But if I do it like this, it doesnt, and I'm getting "const" assertion error.
It doesn't even work if I copy colors array like [...colorsArr] or colorsArr.slice()
How does that work?
断言与对象/数组/字符串/数字文字值一起使用,告诉编译器为这些值保留更具体的类型const。它不能像另一个变量一样应用于任意表达式;这是有记录的警告。
如果你写
const colors = ["white", "red", "blue"] as const;
Run Code Online (Sandbox Code Playgroud)
readonly ["white", "red", "blue"]然后编译器推断的类型colors。编译器知道该数组每个成员的值和位置,并且它不会让您更改任何内容。
另一方面,如果你离开as const,
const colors = ["white", "red", "blue"];
Run Code Online (Sandbox Code Playgroud)
然后编译器string[]推断colors. 它只是一个数量、值或顺序未知的字符串数组。这通常是人们想要的,因为也许你想写colors.push("purple")。但编译器完全忘记了特定的字符串文字colors以及它们的顺序。那个信息消失了。
你不能写
const colors2 = colors as const; // error
Run Code Online (Sandbox Code Playgroud)
并让它做任何事情。即使没有编译器错误,它仍然不会产生任何有用的效果。的类型colors是string[]. 写入colors as const无法检索之前丢弃的类型信息。那个信息消失了。充其量你colors2也能得到string[]。
type Colors= typeof colors[number];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1988 次 |
| 最近记录: |