DEV Community

Visakh Vijayan
Visakh Vijayan

Posted on

Contradiction in TS Types

I was curious to know what happens if you do an intersection of two types that have the same property but with different types. For e.g.

type A = { age: number };
type B = { age: string };

type C = A & B;

const c: C = { age: 10 };
Enter fullscreen mode Exit fullscreen mode

This doesn't work. The age in type C is assigned a type of never. This is because there is no value that can satisfy the condition of a number and a string at the same time. Hence it can never have a value.

If you still want to have a type that can take either a number or a string you can go ahead with a union type like so -

type C = A | B;

const c: C = { age: 10 };
Enter fullscreen mode Exit fullscreen mode

Peace ✌️

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more