Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object

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];
like image 288
Bruno Pintos Avatar asked Jan 20 '21 17:01

Bruno Pintos


People also ask

Can we use literal types as const assertions?

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:

What happens if we use const assertions in JavaScript?

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:

What is a const assertion in C++?

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".

How to solve the error “a const enum member can only be accessed?

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.


Video Answer


1 Answers

You can do

let name: keyof typeof myObject

See this question for why strongly typing Object.keys might be a bad idea.

like image 135
Rubydesic Avatar answered Nov 01 '22 22:11

Rubydesic