How to create a type from a variable in Typescript?

Asked

Viewed 55 times

1

I need to create a type that, according to the variable value, uses a specific type.

I have the following constant variables:

const NEW = 'NEW_PROJECT';
const DELETE = 'DELETE_PROJECT';

The code is working with the following type, defined with string types:

type ProjectsActionsType =
  | { type: 'NEW_PROJECT'; payload: { id: string } }
  | { type: 'DELETE_PROJECT'; payload: { id: string } };

But I want to use the constant variable type instead of string types.

I tried this:

type ProjectsActionsType =
  | { type: NEW; payload: { id: string } }
  | { type: DELETE; payload: { id: string } };

But it didn’t work; I received this error:

'NEW' refers to a value, but is being used as a type here. ts(2749)

How can I use variables in Typescript type settings values?

1 answer

1


At type level, the operator typeof returns the type (if present) of its operand value.

For example:

const foo = "FOO_STRING";
type Derived = typeof foo; // tipo inferido é: "FOO_STRING"

See more on typescript documentation.


Be careful not to confuse with the operator typeof javascript, which does not operate at type level, but Runtime.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.