BluePrint
BluePrint

Reputation: 2134

React Typescript: Exporting types containing enums

I have the following files:

CarBrands.ts:

export enum CarBrands {
  SAAB = "saab",
  VOLVO = "volvo"
}

CarBrand.ts:

import {CarBrands} from "./CarBrands";

export type CarBrand = CarBrands.SAAB | CarBrands.VOLVO;

Car.ts:

import {CarBrand} from "./CarBrand";

export default interface Car {
  brand: CarBrand;
}

DefaultCar.ts:

import Car from "./Car";

export const DefaultCar: Car = {
  brand: "volvo"
};

In the last file where I am exporting "DefaultCar" I get the following error: TS2322: Type '"volvo"' is not assignable to type 'CarBrands' even though "brand" should be of type "CarBrand" and not "CarBrands". Why is this?

I have also tried export type CarBrand = typeof CarBrands.SAAB | typeof CarBrands.VOLVO; but this did not work either.

I'm probably missing something obvious, but googling did not help me at all. What am I doing wrong?

Upvotes: 1

Views: 206

Answers (1)

crashmstr
crashmstr

Reputation: 28573

Unless you have a lot more entries in your enum and you don't want them in CarBrand, why not use the enum directly?

Also, even though the enum is string based, you cannot assign a string to the property without a cast. Instead, use CarBrands.VOLVO

import {CarBrands} from "./CarBrands";

export default interface Car {
  brand: CarBrands;
}
import Car from "./Car";

export const DefaultCar: Car = {
  brand: CarBrands.VOLVO
};

Simplified TypeScript Playground

If you would prefer, you could instead just use strings like this:

export type CarBrand = 'saab' | 'volvo';

And in that case, your property assignment of 'volvo' would work because it is a matching string.

Upvotes: 1

Related Questions