Live data from Hacker News

Tricks I wish I knew when I learned TypeScript

cstrnt.dev

111–120 of 276 posts

Re: Tricks I wish I knew when I learned TypeScript

#111
post #96

Earlier quoted context omitted.

> Everything that TS does JS libraries do better Which ones do you need to do everything TS does? > without the horrible tradeoffs Which tradeoffs are horrible?

For example if you want prop types you use propTypes. In React TS replaces good error handling for horrible obscure errors and slows down development considerably etc. etc.

propTypes does runtime type checking, which is a different kettle of fish from static type checking.

The advantage to static type checking is that it removes the performance cost of runtime type checking where it's unnecessary; the language's rules make it impossible to build some constructs where the wrong types get mashed together. The tradeoff is that you have to code so the wrong types don't get mashed together (which is, arguably, your goal in the first place).

You can do everything a statically-typed language does in a non-statically-typed language via best practices, but that's a bit like saying you can do everything a compiled language does in assembly via emulating what the compiler would output. In theory, the compiler is saving you the headache of doing that (but depending on the size of what you're trying to write, sometimes it is simpler to write it in JavaScript and skip the type safety. That code is harder to grow, but not all code grows!).

Re: Tricks I wish I knew when I learned TypeScript

#112

Earlier quoted context omitted.

I found that pattern useful when you don't know what the key will be. I have an iOS app that tracks tips, when you add a tip, it's stored in an object like this: type Tips = { [tipGuid: string]: TipObject } which can be rewritten using Record as type Tips = Record That pattern ins't very useful when creating object with known keys but for data structures where the key is either not known or generated it a godsend.

`Record` is a dangerous type, and I would recommend against it. The problem is that it assumes any key is valid and will return a value type. Example: type Tips = Record const tips: Tips = {} tips["hello"] // TipObject, but you actually get undefined It's better to define a Dictionary type like so: type Dictionary = Partial > Then to use: type Tips = Dictionary const tips: Tips = {} tips["hello"] // TipObject | undef…

[deleted]

Re: Tricks I wish I knew when I learned TypeScript

#113

Earlier quoted context omitted.

Typescript is actually a great language. And with those utility types, you can do pretty fun stuff like, for example, you want to mutate a type so that some fields become mandatory: type Ensure = T & { [U in keyof Pick ]-?: T[U] }; class A { foo?: number; bar?: number; baz?: number; } type MandatoryFields = "foo" | "baz"; type B = Ensure ; const b: B = { foo: 42 }; Here, ts will complain that b is missing baz.

Why write code like that, instead of extending the class with a mandatory property? The above code is going to be inscrutable to a lot of engineers, and this isn't something like an ORM where there's a good reason for that.

I'm building a strongly typed form abstraction layer for work. I use code like this to express "if this generic can be undefined, this field is required. Otherwise it cannot be used".

So: FormElement needs to have a "disabled" function, indicating conditions under which it becomes disabled (and absent from the model), while FormElement must not have a disabled function, as it will always be present in the model.

One pitfall of this approach is it requires a lot of trial and error to find the incantation that both works and doesn't swallow error messages.

Re: Tricks I wish I knew when I learned TypeScript

#114
post #109

Earlier quoted context omitted.

I disagree. `null` in TypeScript is equivalent to `None` in many other typed languages. `undefined` in Typescript is like null in other languages, with the caveat that if you’re working to transition an untyped codebase and trying to bring types, there may be a useful place for `undefined` in order to express that there is a lack of safety / strict-handling in that area. I’m still not sure about Error handling, thoug…

Which language has both a "None" and "null"?

javascript, at least, has "undefined" and "null", an infuriating duality of falsiness. PHP also has a notion of not being set as well as being set but null.

Re: Tricks I wish I knew when I learned TypeScript

#115

Is there ever a reason to use interface over type? From what I’ve seen it looks like they can both do the same thing but with slight differences in syntax

I prefer types over interfaces because of one simple difference: if you use vs code and hover over type alias, it expands it and shows everything inside, while for interfaces it just shows the name.

Re: Tricks I wish I knew when I learned TypeScript

#116
post #96

Earlier quoted context omitted.

For example if you want prop types you use propTypes. In React TS replaces good error handling for horrible obscure errors and slows down development considerably etc. etc.

propTypes does runtime type checking, which is a different kettle of fish from static type checking. The advantage to static type checking is that it removes the performance cost of runtime type checking where it's unnecessary; the language's rules make it impossible to build some constructs where the wrong types get mashed together. The tradeoff is that you have to code so the wrong types don't get mashed together (…

So the whole baroque arhitecture is there to 'remove performance costs'? That's an even worse reason to use TS than avoiding prop type bugs.

Re: Tricks I wish I knew when I learned TypeScript

#118

Note: don't use typeof x === 'object' to check whether something is a valid object, because it will return true for arrays as well. Arrays are objects, so this is expected behaviour.

The core problem here is that you don't actually want to check if something is an object, but whether it matches the Human type. The correct way to do that is to define a type guard [0], for example:

  function isHuman(input: any): input is Human {
    return (
      Boolean(input) &&
      Object.prototype.hasOwnProperty.call(input, "name") &&
      Object.prototype.hasOwnProperty.call(input, "age")
    );
  }
There are libraries which can automate this for you which is the route I would recommend if you need to do this often. As you can see, the code to cover all edge cases such as `Object.create(null)` etc is not trivial.

[0] https://www.typescriptlang.org/docs/handbook/advanced-types....

Re: Tricks I wish I knew when I learned TypeScript

#119
post #90

Earlier quoted context omitted.

This seems extremely hard to read for me, I would have an hard time trying to understand what it does if I found it in any source code

type Ensure I define a type called Ensure This type takes two type parameters, one called T and the other K which will consist of Keys belonging to the type T (in our case, "foo", "bar" or "baz"). = T & This new type (called Ensure) will be equal to the union of two types: One will be T and the other will be: { [U in keyof Pick ] A new type which keys will be picked among the key listed in K -? To which we will remov…

This feels like considerable cognitive load for any developer that needs to work in more than one language.

Re: Tricks I wish I knew when I learned TypeScript

#120
post #96

Earlier quoted context omitted.

> Everything that TS does JS libraries do better Which ones do you need to do everything TS does? > without the horrible tradeoffs Which tradeoffs are horrible?

For example if you want prop types you use propTypes. In React TS replaces good error handling for horrible obscure errors and slows down development considerably etc. etc.

I'm really glad proptypes are not used anymore, ts is simply better. It's more flexible, gives stronger guarantees in some cases (PropTypes.func does zero checks for signature, for example), better support in editors, better integration with other libraries, allows typing hooks/context. If you need runtime checks, use io-ts or runtypes.
Post reply on HN