-1

I'd like to know how to convert array of string variable to type script types.

Note: There are two SO answers already that deal with this but strings are passed hardcoded to keep values of strings as they are.

Both answers pass an array in-line to keep string values in array as literals. But when you pass an array as a variable, it fails to work.

Passing values in-line works.

Edit TypeScript - Array to Literal - Hardcode works in-line works

But passing values as a variable doesn't work

Edit TypeScript - Array to Literal - Doesn't work enter image description here

Question

So how do you create a type to limit a list of allowable string values in domElements as a variable to asLiterals?

1 Answer 1

1

When an array literal is assigned to a variable, it is widened to match the typical behavior.

Because of that, the variable domElements is of type string[] instead of ('a' | 'div' | ...)[]

The answer is in your own code. Use a similar function as your asLiterals() to create a literal array.

export function literalArray<T extends KeyTypes>(...entries: T[]): T[] {
    return entries
}

You can also find this function in the type-plus library.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @unional about widened type behavior. I've tried it with literalArray after installing type-plus but the DOMType is still recognized as string. imgur.com/a/uwQcF8Y. (codesandbox.io/s/7j15z1o856) What could I be missing?
After it is widened, there is no automatically way to narrow it down. I.e, you have to in-line it. Your domElements and arr are the same. Only type is different.
Thank you for the clarification 👊. I will in-line the code as a last resort for my library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.