News for hackers. Stuff that matters.
Re:Problems with TypeScript by valand on Wednesday January 15, 2020 @01:15PM (#22056739)
Guaranteed almost 100% type soundness!!! Non TypeScript user will hate this.

Config it to maximum strictness!

Add in runtime type checks Parse, don't validate https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-va...

Bring type to business logic, e.g.

RegisteredUser { userId: number, email: string }

AnonymousUser { userId: number, email: null }

User = RegisteredUser | AnonymousUser

Handle errors ala Rust,

Return errors/errortype rather than throws

Utilize structure to determine result, e.g.

Failure { error: Error, value: null }

Success<T> { error: null, value: T }

It is worth it. My experience with TypeScript is a whole lot different.

Conspiracy theory inducing facts:

- LogRocket's main use is monitoring bugs in browser application

- Airbnb is LogRocket's customer

Re:Problems with TypeScript by eeperson on Wednesday January 15, 2020 @04:23PM (#22058785)
Do you mean:

    Failure { error: Error }
    Success<T> { value: T }
I assume you want value or error not value and error.
Re:Problems with TypeScript by valand on Wednesday January 15, 2020 @08:14PM (#22060736)
Limitation in TypeScript. Even in TS 3.6.x you can't do

```

if (result.error) { ... }

```

on a variable that possibly returns { value: T }

It'll complain that result may possibly have no attribute error

Re:Problems with TypeScript by paulddraper on Thursday January 16, 2020 @12:43AM (#22061982)
The discriminated union pattern is better [1]

    type Success<T> = { type: 'success', value: T};
    type Error = { type: 'error', value: string };
    type Result<T> = Success<T> | Error;

    if (result.type === 'error') {
      result.error;
    } else {
      result.value;
    }
[1] https://www.typescriptlang.org/docs/handbook/advanced-types....
Re:Problems with TypeScript by sondang on Wednesday January 15, 2020 @09:12PM (#22061071)
You can do:

  if ('error' in result) {
    console.error(result.error); // ok: result inferred as 'Failure' 
  } else {
    doThings(result.value) // ok: result inferred as 'Success<T>'
  }


Even though you used string there, it's pretty type-safe because if you have a typo in your string, the inferred types will propagate other type errors

  if ('errors' in result) { // typo
    console.error(result.errors); // Type error: result inferred as 'never' 
  } else {
    doThings(result.value) // Type error: result inferred as Success<T> | Failure
  }
Re:Problems with TypeScript by felipellrocha on Thursday January 16, 2020 @01:09AM (#22062070)
...

What do you expect here? The compiler is doing exactly what is expected.

Re:Problems with TypeScript by holtalanm on Wednesday January 15, 2020 @05:45PM (#22059654)
eh. the pattern he is trying to mimic from elixir is:

{:ok, value}

or

{:error, err}

so, you would be correct.

Re:Problems with TypeScript by dkdbejwi383 on Wednesday January 15, 2020 @01:22PM (#22056835)
I'm interested in the way you describe handling errors here. Do you have any real world examples you can point me to? Thanks
Re:Problems with TypeScript by valand on Wednesday January 15, 2020 @01:46PM (#22057090)
I would have gladly shown it to you, but almost all my code is proprietary

Here's a small example:

```

function fetchCurrentWeather(){ return fetch(...) .catch(() => ({ error: new NetworkError(), value: null}) .then(res => res.json()) .then(maybeWeather => Weather.is(maybeWeather) ? { value: maybeWeather, error: null} : { error: new DecodeError(), value: null}) .catch(() => ({ error: new DecodeError(), value: null})) }

// And then you use it somewhere in you react app

async initialFetch(){ try { if (this.state.isLoading) return; this.setState({ isLoading: true, weather: null, error: null }); this.setState({ weather: await fetchCurrentWeather().then(reault => { if (result.error) throw result.error; return result.value; }) }); } catch (error) { this.setState({ error }) } finally { this.setState({ isLoading: false }); } }

render(){ return ( <div> {this.state.isLoading && ...} {this.state.weather && ...} {this.state.error && ...} </div> ) }

```

Re:Problems with TypeScript by pdyck on Wednesday January 15, 2020 @02:30PM (#22057579)
Why is this better than throwing errors or using Promise.resolve()?

I know it is inefficient because creating a new error with a stack trace each time is bad for performance. However, you can also throw errors which do not extend Error to avoid this. Destructuring the output and explicitly checking for errors every time seems to be quite the hassle.

Re:Problems with TypeScript by JamesSwift on Wednesday January 15, 2020 @05:01PM (#22059240)
Because the error/success is encoded in the type, you are forced to handle the error case. If you aren't also wrapping throwable functions in `try/catch` then you have a lot of unhandled error cases.

If you know that something truly isn't going to error then you can just force cast it as `foo as Success<T>`. That will still blow up at runtime if its not a `Success`.

Alternatively, you could introduce a monadic chaining that is able to pipe `Result<T>` objects through many functions then handle at the end.

Re:Problems with TypeScript by threatofrain on Wednesday January 15, 2020 @02:44PM (#22057704)
Seems quite like Go.
Re:Problems with TypeScript by valand on Wednesday January 15, 2020 @01:48PM (#22057116)
Darn, sorry for the bad format. Typing this from phone. I guess you gotta copy that to your editor and apply some formatter.
Re:Problems with TypeScript by aecorredor on Wednesday January 15, 2020 @01:46PM (#22057095)
Check out the chapter on handling errors in the book “Programming TypeScript”, it gives a solid pattern for achieving something very close to Rust’s Option.
Re:Problems with TypeScript by TomMarius on Wednesday January 15, 2020 @04:12PM (#22058638)
I would like to recommend fp-ts over other JS/TS functional libraries, already contains types like Option
Re:Problems with TypeScript by meheleventyone on Wednesday January 15, 2020 @01:53PM (#22057177)
I did this super simple version of a Result and Optional types you can of course go further: https://gist.github.com/meheleventyone/b7b504052c589829885fe...
Re:Problems with TypeScript by nesarkvechnep on Wednesday January 15, 2020 @01:27PM (#22056885)
Check out the Either monad in Haskell. It has an implementation in the JS library funfix.
Re:Problems with TypeScript by sj3k on Wednesday January 15, 2020 @04:40PM (#22059004)
I started doing the Fail and Success type pattern after learning about it in Elixir/FP world. Its been a lifesaver