11 ms·
TypeScript: Control flow analysis for destructured discriminated unions
- sizediterable 5y agoAlso: https://github.com/microsoft/TypeScript/pull/46429 https://github.com/microsoft/TypeScript/pull/46429. Anders is on a roll!
- sakesun 5y agoAny body know what is @typescript-bot ? How to setup one for my project ? @typescript-bot pack this @typescript-bot test this @typescript-bot user test this @typescript-bot run dt @typescript-bot perf test this
- Master_Odin 5y agoIt's probably a simple bot that's hooked up to a GH app. Then just some custom code to react to specific types of events. Depending on what you need done, you'd possibly be able to replicate a lot of functionality within a GH action.
- orta 5y agoYep, that is exactly what it is, just a simple GH webhook to azure develops / GitHub Actions trigger. https://github.com/microsoft/TypeScript/issues/46177#issuecomment-933779614 https://github.com/microsoft/TypeScript/issues/46177#issueco...
- capableweb 5y agoSeems like a good way of adding additional comment spam to your projects. What happened with having a GUI with audit logs that you can click a button/make a curl request to in order to trigger? God, 19 out of 22 comments are all about CI and should not even be in the PR. How can people effectively work with so much noise in their PRs?
- maxfurman 5y agoWow. More impressive work by the Typescript team! AFAICT this will have the most impact on folks using Typescript with Redux stores and similar dispatchers.I know I would have liked having this feature back when I was doing that work.
- NaughtyShiba 5y agoDefinitely a help. It should make it easier to use with payloads in postMessage too.
- tshaddox 5y agoI believe this will also obviate a common recommendation to not destructure when using React Query: https://tkdodo.eu/blog/react-query-and-type-script#type-narrowing https://tkdodo.eu/blog/react-query-and-type-script#type-narr...
- dragosmocrii 5y agoThanks for sharing this. I literally ran into the same issue yesterday, and was wondering why TS can't understand that I am discriminating on the isSucces property.
- tkdodo 5y agoI’ll definitely update that article once the new TS version is released :)
- the_duke 5y agoNote that this already worked fine by just operating on the field. Like `if (action.kind === 'x')` / `switch (action.kind)`. This "only" extends support to destructured discriminators. Definitely nice to have, but of limited impact.
- acemarke 5y agoFWIW, our standard recommended Redux usage patterns for the last couple years have specifically _not_ needed switch statements to determine how to handle an action, because our official Redux Toolkit package has a `createSlice` API that lets you define case reducers as simple functions in an object. `createSlice` then generates all the action types internally, generates corresponding action creator functions, and handles calling the right case reducer when that action is dispatched. Additionally, RTK has been designed to work great with TypeScript. Typically all you need to declare is the type of the state for that slice, and the payload for each reducer's action, and everything else is inferred. See our Redux docs tutorials for details: https://redux.js.org/tutorials/essentials/part-2-app-structure#creating-slice-reducers-and-actions https://redux.js.org/tutorials/essentials/part-2-app-structu... https://redux.js.org/tutorials/fundamentals/part-8-modern-redux#writing-slices https://redux.js.org/tutorials/fundamentals/part-8-modern-re... https://redux.js.org/tutorials/typescript-quick-start https://redux.js.org/tutorials/typescript-quick-start
- the_gipsy 5y agoLooks like pattern matching!
- NaughtyShiba 5y agoKinda like that. Simple example: Lets say you can submit one of these payloads { type: 'SET_PERSON', payload: Person } and { type: 'SET_AGE', payload: number } Based on what type field equals to, TLS (Typescript Language Server - used by IDEs) and TSC (TypeScript Compiler) will know type of payload. It’s already possible to achieve that to some extent, but it’s really limited.
- the_gipsy 5y agoI love that TypeScript never stops pushing type safety.
- arxanas 5y agoExplanation: A record is a set of key-value pairs with the value having a given type (also called a struct, object, etc. depending on the context). In TypeScript, this is an example of a record: const foo = { bar: 1, baz: "qux" }; Destructuring is an ergonomic feature where you can take the fields of a record and assign them to local variables. For example: // Equivalent to // const bar = foo.bar; // const baz = foo.baz; const { bar, baz } = foo; Besides ergonomics, destructuring can offer features like exhaustiveness-checking, to make sure that you used all of the fields of a record. A union type is a type which denotes that the value is one of two different types, indicated like this: type Foo = number | string; Sometimes, you have two different cases with the same type, and you want to distinguish between them. For example: // Not helpful -- we can't tell from the value // whether it's supposed to be a username or an email. type UsernameOrEmail = string | string; To handle this case, you can use a discriminated union instead. These unions have a special value which unambiguously indicates which case is present: type UsernameOrEmail = { type: "username", value: string } | { type: "email", value: string }; Sometimes, you have a discriminated union with different fields: type ApiRequest = { type: "message", subject: string, contents: string } | { type: "view-posts", user_id: number }; Currently, TypeScript uses control-flow analysis to ensure that you're using the right kinds of fields depending on the discriminator value: const request: ApiRequest = getRequest(); if (request.type === "message") { // Okay: console.log("Subject is", request.subject); // Rejected by compiler: console.log("User ID is", request.user_id); } However, you can't combine this feature with destructuring: type Action = { kind: "A", payload: number } | { kind: "B", payload: string }; const { kind, payload } = getAction(); if (kind === "B") { // Not currently allowed: payload.toUpperCase(); } With this pull request, you can do the above. This can be convenient with patterns like reducers (see https://github.com/microsoft/TypeScript/issues/46143 https://github.com/microsoft/TypeScript/issues/46143 for an example).
- dekerta 5y agoThanks for the explanation. I've been programming for many years, and your examples make total sense to me, but reading sentences like "Control flow analysis for destructured discriminated unions" make me feel like a total impostor
- aluminum96 5y agoIt's really cool that this is possible. TypeScript has developed an incredibly advanced type system in only a few years.
- randomdata 5y agoBut there is always that coworker who still insists on using any.
- capableweb 5y agoCommon problem with emerging technologies (such as TypeScript for JavaScript development) is that many junior or even intermediate developers try to shoehorn their "newly learned about tech" into every single problem, slowing everyone and everything down because of this hype-chasing. So even for simple applications that won't benefit anything from type checking now gets wrapped in TypeScript. Then some people find that because you're using TypeScript, you need everything to be precisely typed, when you (as a human) might know better and just type the areas where it's the most important, so you can move forward faster. But as always, context is king and no solution fits everything. But hype makes it seem like a tool fits everything, to the detriment of everyone else.
- 015a 5y agoVery nice! The very, very related thing I found myself wishing I had just today is the ability to destructure discriminated union fields which only exist on one component type of the union. As an example, with the following type system: type Output = OutputExists | OutputDoesntExist; interface OutputExists { exists: true, url: string }; interface OutputDoesntExist { exists: false }; The ability to destructure like: const f = ({ exists, url }: Output) => {} Such that, at the time of destructuring: exists: true | false url: string | undefined I believe, with this PR, if we re-structured the types above to: interface OutputDoesntExist { exists: false, url: undefined }; That destructuring would be possible, with all the control flow analysis necessary to make it useful. Today, even that wouldn't be possible, so definitely excited for this change. But, I'm curious if anyone knows if this change can extend to situations where a field isn't even defined in one of the unions, and the compiler can just insert an undefined type for those fields. Or, maybe this would have some unresolveable side-effects I'm not considering.
- gherkinnn 5y agoI repeatedly come across the same issue. So I gave it a try running TS 4.6 Nightly [0] In short: interface OutputDoesntExist { exists: false }; // error, as ever :( 0 - https://www.typescriptlang.org/play?ts=4.6.0-dev.20211103#code/C4TwDgpgBA8grsMCoF5YKcAogDwJYDOwBUAPuoggCID2EBAdtvkQFB5MQBOAZgIYBjaPErNCxKAG8oEFsQBcUYFzgQANFDhcANoqJcOAcygBfdp16DhGanUZiiUmXIKL+2gtDOsBNBo55UKAAKaVlxAg0tbVNFEUwASlQAPilvViA https://www.typescriptlang.org/play?ts=4.6.0-dev.20211103#co...
- eyelidlessness 5y agoWhat I do: interface OutputDoesntExist { exists: false; url?: never; } Now it’s: - Optional in the union type - Always present and has the correct type in the exists: true case - Still optional in the exists: false case, but if you try to access it you always get a type error
- 015a 5y agoI like the use of 'never' over just 'undefined'; really drives home that not only is it not there, but it shouldn't exist at all in that case. I'm trying to think of a reason why the compiler couldn't allow that destructuring, implicitly type the values missing in some components of the union as 'T | ... | never', then lean on the control flow analysis it looks like we're getting in 4.6 to specify the type as the discriminated union is de-discriminated (lol). JS itself does allow the destructuring of elements missing from an object, they come out as undefined, so I don't believe there'd be any underlying issues. Hopefully we see it in 4.7!
- 19h 5y agoSomething I am absolutely missing from TypeScript is enums with associated data like in Rust: https://doc.rust-lang.org/reference/items/enumerations.html https://doc.rust-lang.org/reference/items/enumerations.html. The usefulness of this obviously depends on pattern matching control flow ops in Rust that don't exist in TypeScript but it would make my life just so much easier.
- brundolf 5y agoYou can do a similar thing with discriminated unions in TS, with some caveats mainly around ergonomics. You can even get exhaustiveness checking with a little trickery Edit, example of exhaustiveness checking: switch(obj.kind) { case "one": return ... case "two": return ... case "three": return ... default: // @ts-expect-error throw Error("Didn't cover " + obj.kind) } This will actually err at compile time if you missed a case, because otherwise obj.kind will have type "never", which will cause a type error on that line, which will be expected due to the directive comment. If obj.kind is not "never", the code will not have an error, and so the directive will cause an error. ...it is definitely preferable having language-level support for this stuff though.
- matt_kantor 5y agoIn most situations you don't even need a default case: https://tsplay.dev/NlpBGN https://tsplay.dev/NlpBGN
- Waterluvian 5y agoHelp me understand this feature. How does it differ from a discriminated union of object types? (I might be completely misunderstanding the feature you’re raising)
- tshaddox 5y agoTS discriminated unions are functionally nearly identical to variants in OCaml and enums in Rust. I don't know about Rust, but the difference between TS and OCaml is mainly just the syntax and ergonomics. OCaml has great syntax for pattern matching and exhaustiveness checking, for example. You can still get this functionality in TS with if/else or switch statements and potentially some type system tricks: https://www.fullstory.com/blog/discriminated-unions-and-exhaustiveness-checking-in-typescript/ https://www.fullstory.com/blog/discriminated-unions-and-exha... To illustrate how TS discriminated unions are functionally equivalent, check out this playground link showing how ReScript (an alternate syntax of OCaml which can compile to JavaScript) compiles an OCaml variant to a JavaScript object with a "TAG" key that could easily be typed as a discriminated union in TypeScript: https://rescript-lang.org/try?code=C4TwDgpgBAThCOBXCBnYBlYBDYiVQF4oAfKAGQHssATASwDsBzEqdRAY3dRQAo0YGjAJQsAojBgUYAYQrUIPBsCEBuAFBqANhGCwAjIXJU6Tddt0wATIbaduPAEQB1CJvYUAthACEDoVp1YAGZDcUkZOQUAVgAGGKEgA https://rescript-lang.org/try?code=C4TwDgpgBAThCOBXCBnYBlYBD...
- bluepnume 5y agoI was a Flow holdout for the longest time. TypeScript's support for discriminated unions is one of the things which finally won me over. Super glad to see it being improved upon here.
- gherkinnn 5y agoAs somebody who never worked with Flow but loves TS, what does Flow offer that the latter can’t do?
- GeZe 5y agoAnother example would be the difference between their enum features: https://medium.com/flow-type/typescript-enums-vs-flow-enums-83da2ca4a9b4 https://medium.com/flow-type/typescript-enums-vs-flow-enums-... "TypeScript Enums vs. Flow Enums"
- nsonha 5y agoit has some nice features that ts doesn't have: opaque types (can be done by nominal tying in ts). More stringent JSX, but only slightly. I think that's it these days. Flow used to have (slightly) more features but now TS has way more already and even more to come. The Flow people moved on to Recript, or whatever name they call it these days.
- GeZe 5y agoFYI, it would not be accurate to say that "The Flow people moved on to ReScript".
- eyelidlessness 5y agoNominal/opaque primitive types. You “can” do it with hacks but it’s some kind of a fib and depending on approach it’s less type safe.
- inbx0 5y ago1. And biggest for me: Exact types function x(y: { foo: number, bar?: number }) {} const y = { foo: 1, baar: 2, // typo } x(y) The above is caught in Flow when exact types are enabled but not in TS. TS issue https://github.com/microsoft/TypeScript/issues/12936 https://github.com/microsoft/TypeScript/issues/12936 TS has a concept of "freshness" which catches some of these mistakes when you construct y right in the arguments of x, but it gets easily broken by accident and without a warning. 2. Nominal types, so you can have for example "Id" type that is a number but not to be mixed with other numbers, you can't just call a function that expects an Id with literal 42. Classes are nominal too, which I think is a solid choise. 3. Type variance & related safeguards function x(y: { foo: string | number }) { y.foo = 1 } const y: { foo: string } = {foo: 'a'} x(y) y.foo.toUpperCase() Caught by Flow but not TS. 4. Local call site type inference of function argument types, so you can have some helper functions within a file that you don't need to explicitly annotate, and Flow will happily infer types based on how you call it. 5. Performance has gotten prerty good with recent versions, to the point where I suspect it's faster than TS. I don't have any hard data on this though. Even though in many many ways Flow is worse than TS, we have still stuck with it, and that's only like 80% because it'd be s huge undertaking to make the switch. 20% is because some of these features are actually nice :)
- revskill 5y agoThis is sweet ! Now i can truly have the Strategy pattern implemented with TS.
- adamddev1 5y agoYes! I also found myself wishing for this very feature. TypeScript continues to get more and more awesome.
- htunnicliff 5y agoThis is awesome! Thank you to the PR author for working on this — it is one of the most common pain points I have encountered when writing TypeScript.
- jim-jim-jim 5y agoIt's encouraging seeing all the work going into making tagged unions a natural part of TS. I've tried to introduce them multiple times, and have been shot down by my team on every attempt. I think they still come across as "hacky," and more JS-minded people who are totally cool validating with if-else everywhere still can't appreciate the benefits of annotating data in this manner. I hope TS eventually arrives at a standard, low impact way to create and manipulate such structures; maybe more people will be on board then. It looks like we're moving in the right direction.
- dgreensp 5y agoWell, tagged unions, like many TS features, are designed to enable type-checking on vaguely idiomatic JS code, aren't they? That checks properties of objects in if-else statements? It sucks that people aren't open to defining their structures in a way that aids type-checking, if that's what you mean!
- jim-jim-jim 5y agoI understand that familiarity is TS' selling point, but that dreadful I-word was actually used against me when trying to introduce these unions. For whatever reason, some people don't find the syntax very natural at the moment. With no standard convention around the tag's name (it is `kind` in the linked PR, but I've seen it specified in many other ways), my suggestion came across like a cute self-invented gimmick rather than a fundamental concept in programming. Others had trouble differentiating the tag's literal type from a vanilla string due to the quotes. If some of the noise were eventually removed and tagged unions became true first class citizens in TS' syntax, I think some of these colleagues without as much typing experience might be more open to the idea—or at the very least understand it in the first place.
- andrewflnr 5y agoI love discriminated unions, but bounced off the typescript approach because it looked like too much of a pain to actually be worth it. Hopefully features like this can make it worthwhile, because I really miss them.
- matsemann 5y agoOne thing I'm wondering: with all the bells and whistles and insanely complex things TS now supports, why does it still fail to catch seemingly simple mistakes? For instance, it's sooo easy to write a React component taking in another component as a prop and some props for that other component, to rendering it. But somehow lose the type safety of the props being passed in. Like, you write some generics and the compiler stops complaining inside your component. But if you go back out and then try to pass some weird props instead, it doesn't care. I feel it's too easy to write code that looks tyoe safe but subtly isn't.
- valenterry 5y agoI'd say it's two things: 1. Typescript has to work with Javascript, which inherently makes things difficult and you have to choose between correctness or ergonomics. TS went for the latter, which probably was a good decision, otherwise no one would use it now. 2. While I have a lot of respect for the creators of TS, the language is not very consistent and uses a lot of "special cases" or "special features" to solve specific problems. But it also means that it becomes hard to ensure that all these features work together well and in the way that users expect. Other languages lack features that TS offer, but they feel more "consistent" or reliable.
- nuerow 5y ago> [TypeScript] is not very consistent and uses a lot of "special cases" or "special features" to solve specific problems. That's very interesting. Could you please provide an example that showcases that inconsistency?
- valenterry 5y agoThis very post is a good example. Typescript has destructuring and control-flow analysis/refinement. But as you can see from the issues that are fixed by this PR, these two things haven't worked together very well. This comes from trying to fix 1) compiler errors in conditions where the code is safe but the compiler can't understand that and 2) destructuring products/co-products. Even if both features work on their own and help in certain cases, combining them leads to undesired results.