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)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More