loading words...

Jun 10, 2019 23:47:24

major typescript flaw

by @swizecteller | 287 words | 3πŸ”₯ | 116πŸ’Œ

Swizec Teller

Current day streak: 3πŸ”₯
Total posts: 116πŸ’Œ
Total words: 32303 (129 pages πŸ“„)

Today I discovered a major flaw in TypeScript. It's by design so my bad, but it frustrates me nontheless

πŸ‘‰ no run-time typing support. Only static types πŸ’©

---

A use case where you might notice this are type guards.

Say you want to iterate over a mixed type array. Input fields for a form, for example.

function doFieldStuff(field: Text | Email | Password) {

  // decide what to render based on field type

}

---

Ah this is easy! You just check the type of that `field` argument, right?

You do. Sort of ...

What do you think this returns?

function doFieldStuff(field: Text | Email | Password) {

  console.log(typeof field)

}

---

It prints `object` every time. Because the static type might be Text, Email, or Password, but at runtime they're all just objects.

Same thing happens if you try `instanceof`

πŸ’©

---

You can work around this by using objects. Each of Text, Email, and Password corresponds to a JavaScript class.

That allows you to call `instanceof field` and get a useful response.

Instantiating objects just to pass props around is clunky tho

---

Another great approach is a `type` property. Feels silly since you already have types, but it works well

πŸ‘‡

interface Email {

  type: "email";

  name: string;

}


interface Text {

  type: "text";

  name: string;

  placeholder: string;

}


interface Password { 

  type: "password";

  name: string;

  placeholder: string;

  visible: boolean;

}


function (field: Text | Email | Password) {

  switch (field.type) {

   case "text": //...

   case "email": // ...

   case "password": // ...

  }

}


doStuff({ type: "email", name: "userEmail" })

doStuff({ type: "text", name: "firstName", placeholder: "First Name" })

doStuff({ type: "password", name: "password", visible: false })

---

Using the `type` property feels silly, but I love that TypeScript is able to statically analyze that and give you proper support. If your inputs don't match the type, it's gonna tell you.

And at runtime JavaScript still knows what's up πŸ‘Œ

Originally published at twitter.com

contact: email - twitter / Terms / Privacy