Hacker News new | ask | show | jobs
by orif 3305 days ago
TypeScript would complain about that snippet too.

function getOptions() { return { num: 42, str: "val" }; }

var __options__ = getOptions();

type Options = typeof __options__;

var options: Options = {

    ^^^^ Type is not assignable

    num: "hi",
    str: 42
};
1 comments

I love TS and cannot speak enough good things about it.

But in your TS example, the code would execute. Not in the Flow example, where it's just an annotation.

There are hacks and other approaches, documented here:

https://github.com/Microsoft/TypeScript/issues/6606

>But in your TS example, the code would execute.

Incorrect. It's a type alias so it uses "type typeof" not "value typeof". It doesn't have the problem that the issue you linked to is about.

https://www.typescriptlang.org/play/#src=function%20getOptio...

Observe the JS output contains no `typeof` and that the type `Options` is considered to be the same as `{ num: number, str: string }` if you hover over it.

I don't understand. In your transpiled code, getOptions is clearly being called in JS.

In flow, getOptions() wouldn't be in the transpiled code at all.

Imagine the body of getOptions as an extremely expensive computation. Some prime calculation. But you only want its return type. In flow comments, you can get it.

In the approach of your snippet, you could get it, but it will execute the full function with the full price.

My bad, I thought you were referring to `typeof` being the code that still executes. Now I read that tweet more carefully and noticed the `getOptions()` call is in a comment. A strange feature that I suppose is useful when dealing with complex anonymous types, though in my experience such complex types tend to be named.
The minifier would get rid of the __options__, and also the function getOptions because both are not used in the resulting code. You need a minifier in any serious project.
It wouldn't. getOptions() could have side effects that we want to run. Imagine inside of getOptions we have a prompt() call to fill in some of the options...