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];
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]
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?
A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.. I am also not sure what you expect to happen. Theas constoperator is used to narrow down literal types.colorsArris a variable of typestring[]and the type information about specific elements is already lost at that point.constassertions. It only makes sense with literals because that's the only chance you have to preserve their strong types.const x = [0] as constsays "don't throw away the details of the array". Butconst x = [0]infersxasnumber[], and after thatx as constis useless, like asking someone not to throw away last week's trash. It's already gone.