ZiiMakc
ZiiMakc

Reputation: 37034

Conditional typescript property type based on object value

Why typescript doesn't show errors and how to make it work?

Typescript sandbox.

enum Animal {
  BIRD = 'bird',
  DOG = 'dog',
}

interface Smth<T extends Animal = Animal> {
  id: number;
  animalType: T;
  config: T extends 'bird' ? number : string; // if its bird - should be a number
}

const smth: Smth = {
  id: 1,
  animalType: Animal.BIRD,
  config: 1
};

const smth2: Smth = {
  id: 1,
  animalType: Animal.BIRD,
  config: 'x' // should be error
};

if (smth.animalType === Animal.BIRD) {
 smth.config = 1;
 smth.config = 'x'; // should be error
}

// Posible solution, but is it the only one? Look ugly
type Base = {
    id: number
}

type SmthWorking = Base &
  (
    | {
        animalType: Animal.BIRD;
        config: number;
      }
    | {
        animalType: Animal.DOG;
        config: string;
      }
  );

Upvotes: 0

Views: 64

Answers (1)

amirhe
amirhe

Reputation: 2341

You should probably pass Smith a generic type; you can't infer the type from the setting animalType alone.

const smth2: Smth<Animal.BIRD> = {
  id: 1,
  animalType: Animal.BIRD,
  config: 'x' // ⚠️ gives you an error, no error for number
};

Upvotes: 1

Related Questions