DEV Community

Iven Marquardt
Iven Marquardt

Posted on

2

Row Polymorphic Records for More Type Safety in Typescript

Typescript's type system uses structural subtyping and hence allows every data structure for a given type that contains at least the demanded properties.

However, we can easily restrict this less safe polymorphism to row polymorphism by utilizing generics:

type foo = { first: string, last: string };

const o = { first: "Foo", last: "Oof", age: 30 };  
const p = { first: "Bar", last: "Rab", age: 45 };  
const q = { first: "Baz", last: "Zab", gender: "m" };  

const main = <T extends foo>(o: T) => (p: T) => o.first + o.last

main(o) (p); // type checks  
main(o) (q); // type error
Enter fullscreen mode Exit fullscreen mode

Playground

This isn't as type safe as nominal typing but definitively an improvement. Read more in chapter A Little Type Theory of the FP in JS course.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (2)

Collapse
 
allforabit profile image
allforabit

I can't quite see why the second example doesn't type check?

Collapse
 
allforabit profile image
allforabit

Oh now I see it, both T's have to be the same shape.

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay