Object.keys() as const
not working. How can I achieve this? (Suppose I don't know the content of the object, I don't know what keys does my object have)
const values = Object.keys(myObject) as const;
I need the as const
to get string literal types
let name: typeof values[number];
But, if we used as const assertions, this becomes restricted to a readonly Tuple, with "john doe" in the first position and "25" in the second position: Literal types allow us to define types that are more specific, instead of something that is generalized like string or number. For example:
But, if we used const assertions, it will be inferred as a literal type of On: One thing to keep in mind is that const assertions can only be applied to simple expressions. So you can not do something like this:
A const assertion tells the compiler to infer the narrowest* or most specific type it can for an expression. If you leave it off, the compiler will use its default type inference behavior, which will possibly result in a wider or more general type. Note that it is called an "assertion" and not a "cast".
The error "A const enum member can only be accessed using string literal" occurs when we try to access a const enum using an expression or a variable. To solve the error, remove the const keyword when declaring your enum. Here is an example of how the error occurs. We are trying to use a variable (or an expression) to access a const enum member.
You can do
let name: keyof typeof myObject
See this question for why strongly typing Object.keys
might be a bad idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With