[Typescript] - Dynamic string union types in Typescript

Truong Bui

Published on: Last updated:

typescript tips

TABLE OF CONTENTS

  1. Problem
  2. Solution

Problem

I have a string union type like this:

type Status = 'active' | 'inactive' | 'pending';

but Status can be any string, not only active , inactive , pending . How can I define a type that allows any string?

Solution

You can use the following type to allow any string:

type Status = 'active' | 'inactive' | 'pending' | string;

But there is a new problem: we can't use the completion hint anymore

string union without the completion hint

To solve this problem, we can use string & {} retain the completion hint

type Status = 'active' | 'inactive' | 'pending' | string & {};

Now, we can use the completion hint again

string union with the completion hint

Hope you find this article useful. If you have any questions, please let me know in the comment section below. 👇