0

There are two types:

type Car = {
  brand: string
  model: string;
  firstRegistration?: number;
}

type Color = "red" | "blue" | "green";

How can I create new type OtherCar that has brand type from Car together with Color type?

What I have tried:

type OtherCar = {
  brand: Pick<Car, 'brand'>;
  color: Color;
}

function makeCar({ brand, color }: OtherCar): string {
  return `${brand}, ${color}`
}

When calling

makeCar({ brand: 'Opel', color: 'red' });

There is an error - TS2322: Type 'string' is not assignable to type Pick<Car, "brand">.

4
  • The type Pick<Car, "brand"> means "the same thing as the type Car, but only with the brand property). So it's equivalent to { brand: string; }. It seems you just want a string. So use string, not Pick<Car, "brand"> Commented Jan 20, 2020 at 15:15
  • What if I need to do it in a DRY way? If brand changes from string to something else, then I would need to update the type it two places. What would be the right way to reference the type from the Car? Commented Jan 20, 2020 at 15:29
  • See the answer of ford04. Or extract a common interface (Brandable) and extend it. Commented Jan 20, 2020 at 15:31
  • makeCar({ brand: { brand: 'Opel' }, color: 'red' }); This will work cause brand in OtherCar is an object of Car but just with brand property. Commented Jan 20, 2020 at 15:31

1 Answer 1

1

You have nested brand property one level too deep, try out the following instead:

type OtherCar = {
    color: Color;
} & Pick<Car, 'brand'>

const res = makeCar({ brand: 'Opel', color: 'red' }); // Opel, red

Edit: Your OtherCar Pick type in the question looks like this, which is not what you want:

type OtherCar = {
    brand: {
        brand: string;
    };
    color: Color;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Works great!
type OtherCar = { brand: Car['brand'], color: Color }; also works.

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.