2

I have a type IconName that looks like this:

type IconName = 'cars' | 'mars' | 'truck' | 'warning'

I want then to create another type VehicleIconName which contains all icons name related to a vehicle:

type VehicleIconName = 'cars' | 'truck'

But how can I tell to TypeScript that each strings in VehicleIconName have to be of type IconName too?

So that I couldn't write this:

type VehicleIconName = 'cars' | 'truck' | 'invalidIconName'

1 Answer 1

8

You can add a helper type:

type Subset<Parent, Sub extends Parent> = Extract<Parent, Sub>;

type IconName = 'cars' | 'mars' | 'truck' | 'warning'

type VehicleIconName = Subset<IconName, 'cars' | 'truck' | 'invalidName'>

Error on last line:

Type '"cars" | "truck" | "invalidName"' does not satisfy the constraint 'IconName'.
  Type '"invalidName"' is not assignable to type 'IconName'.ts(2344)

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

4 Comments

Yep works like a charm 👍 Do you think it's the only way to achieve this?
@johannchopin: Maybe; at the very least i could not think of another method.
You could improve the Subset type by having it equal to Extract<Parent, Sub> instead of just Sub. Otherwise although the definition of VehicleIconName throws an error, const x: VehicleIconName = "invalidName" would still be a valid assignment.
@ftm: Probably a good idea to report those errors right away, thanks for the suggestion.

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.