3 ms·
TypeScript would complain about that snippet too. function getOptions() { return { num: 42, str: "val" }; } var __options__ = getOptions(); type Options
by orif 9y 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
};
- silviogutierrez 9y agoI 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 https://github.com/Microsoft/TypeScript/issues/6606
- Arnavion 9y ago>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%20getOptions()%20%7B%20return%20%7B%20num%3A%2042%2C%20str%3A%20%22val%22%20%7D%3B%20%7D%0D%0Avar%20__options__%20%3D%20getOptions()%3B%0D%0Atype%20Options%20%3D%20typeof%20__options__%3B%0D%0Avar%20options%3A%20Options%20%3D%20%7B%0D%0A%20%20%20%20num%3A%20%22hi%22%2C%0D%0A%20%20%20%20str%3A%2042%0D%0A%7D%3B 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.
- silviogutierrez 9y agoI 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.
- Arnavion 9y agoMy 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.
- wereHamster 9y agoThe 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.
- silviogutierrez 9y agoIt 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...