214 points · by surprisetalk · 1y ago · 209 comments
type Foo = 'foo' | 'bar';
const myFoo: Foo = 'foo';
switch (myFoo) {
case 'foo':
// do stuff
break;
default:
myFoo satisfies never; // Error here because 'bar' not handled
}It is meant to be a much better alternative to Javascript while dealing with the fact that the underlying engines use and existing programmers were used to Javascript.
That said I absolutely enjoy TypeScript, but that might be because I suffered from having to deal with Javascript from 2006 until TypeScript became available.
Writing TypeScript is better than JavaScript, but the lack of runtime protection is fairly problematic.
However, there are libraries such as https://zod.dev, and you can adopt patterns for your interfaces and there's already a large community that does this.
The "impossibility" is just a trait of the type definitions and assertions that developers specify. You don't need to use TypeScript to understand that impossibilities written in by developers can and often are very possible.
What I mean to say is - TypeScript isn't proof.
```ts
/*
* A function that asserts that a value is never.
* Useful for exhaustiveness checks in switch statements.
*/
export function assertNever(x: never): never {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`Unexpected object: ${x}`)
}```
It also makes match expressions an expression rather than a statement, so it can replace awkward terenaries. And it has no transitive dependencies!
Previously you could define a function that accepted never and throws. It tells the compiler that you expect the code path to be exhaustive and fixes any return value expected errors. If the type is changed so that it’s no longer exhaustive it will fail to compile and (still better than satisfies) if an invalid value is passed at runtime it will throw.
But unfortunately, using a default clause creates a branching condition that then treats the entire switch block as non-exhaustive, even though it is technically exhaustive over the switch target. It still requires something like throwing an exception, which at that point you might as well do 'const x: never = myFoo'.
class AbsurdError extends Error {
constructor(public value: unknown, message: string) {
super(message);
this.name = 'AbsurdError';
}
}
function absurd(value: never, message: string) {
throw new AbsurdError(value, message);
}
Including an error message and an error type helps if one does slip through to runtime. Additionally, the AbsurdError can be caught and escalated appropriately. And finally the absurd function can be used in an inline ternary etc. where alternatives like throw cannot.An extremely steep one.
The average multi-year TypeScript developer I meet can barely write a basic utility type, let alone has any general (non TypeScript related) notion of cardinality or sub typing. Hell, ask someone to write a signature for array flat, you'd be surprised how many would fail.
Too many really stop at the very basics.
And even though I consider myself okay at TypeScript, the gap with the more skilled of my colleagues is still impressively huge.
I think there's a dual problem, on one side type-level programming isn't taken seriously by the average dev, and is generally not nurtured.
On the other hand, the amount of ideas, theory, and even worse implementation details of the TypeScript compiler are far from negligible.
Oh, and it really doesn't help that TypeScript is insanely verbose, this can easily balloon when your signatures have multiple type dependencies (think composing functions that can have different outputs and different failures).
To be clear, an array flat type:
type FlatArr<Arg extends unknown[]> = Arg extends [infer First, ...(infer Rest)] ?
First extends unknown[] ?
[...First, ...FlatArr<Rest>] :
[First, ...FlatArr<Rest>] :
[];
is far from basic Typescript. The average Typescript dev likely doesn't need to understand recursive conditional types. It's a level of typescript one typically only needs for library development.Not only have I never been expected to write something like this for actual work, I'm not sure it's been useful when I have, since most of my colleagues consider something like this nerd sniping and avoid touching/using such utilities, even with documentation.
Now, that said, I probably would want to be friends with that dev. Unless they had an AI generate it, in which case the sin is doubled.
RXJS’s pipe function has a pretty complex type for its signature, but as a user of the library it ‘just works’ in exactly the type-safe way I’d expect, without me having to understand the complexity of the type.
As someone who came from a CS background, this kind of attitude is deeply mysterious. That seems like a type expression I'd expect a CS undergrad to be able to write - certainly if an SDE with 1-2 years experience was confused by it, I'd be advocating against their further promotion.
Especially when it comes to signatures in Typescript, complex signatures can be used to create simple and ergonomic APIs.
But anyway you shouldn’t be allowed to push anything like this without multiple lines of comments documenting the thing. Unreadable code can be balanced with good documentation but I rarely saw this unfortunately.
If you're writing first-party software, it probably doesn't matter. But if you have consumers, it's important. The compiler will tell you what's wrong all downstream from there unless someone explicitly works around it. That's the one you want to reject.
type Flatten<T> = T extends Array<infer U> ? Flatten<U> : T
> The average Typescript dev likely doesn't need to understand recursive conditional types.The average X dev in Y language doesn't need to understand Z is a poor argument in the context of writing better software.
It's a good response to the claim that we'd be surprised at how many would fail to do this, though.
function flat() { // type FlatArr<Arg extends unknown[]> =
let [first, ...rest] = this;
return (this.length > 0) ? // Arg extends [infer First, ...(infer Rest)] ?
Array.isArray(first) ? // First extends unknown[] ?
[...first, ...flat(rest)] : // [...First, ...FlatArr<Rest>] :
[first, ...flat(rest)] : // [First, ...FlatArr<Rest>] :
[]; // [];
}
If you want to unternarise it: function flat() {
if (this.length > 0) {
let [first, ...rest] = this;
if (Array.isArray(first)) {
return [...first, ...flat(rest)];
} else {
return [first, ...flat(rest)];
}
} else {
return [];
}
}
I still wouldn’t call it basic TypeScript, but it’s not conceptually that advanced, you just need to know about infer and extends.Now in reality, Array.prototype.flat has a more complex definition, partly because (like most of Array’s methods) the method is generic (it works on array-like objects that have a length property and numeric indexing), and partly because of the depth parameter. From lib.es2019.array.d.ts:
type FlatArray<Arr, Depth extends number> = {
done: Arr;
recur: Arr extends ReadonlyArray<infer InnerArr> ? FlatArray<InnerArr, [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][Depth]>
: Arr;
}[Depth extends -1 ? "done" : "recur"];
interface ReadonlyArray<T> {
// [Snipped: flatMap, and flat’s doc comment]
flat<A, D extends number = 1>(
this: A,
depth?: D,
): FlatArray<A, D>[];
}
// [And repeated for interface Array<T>.]
Ouch. Don’t like the { done, recur }[Depth extends -1 ? "done" : "recur"] at all, no idea why it wasn’t written as `Depth extends -1 ? Arr : Arr extends ReadonlyArray<…`. And as for hard-coding support for depths up to 20 then bailing… probably pragmatic, it’s possible to support all values, but rather messy: https://stackoverflow.com/q/54243431.In other words, if you flatten `[string, [string, number]]` my example would give you `[string, string, number]` whereas the one in lib.es2019.array.d.ts would give you `(string | number)[]`
(my example, on the other hand, would only flatten a depth of 1, though a completely flattened type instead of just depth 1 could be represented by changing `[...First, ...FlatArr<Rest>] :` to `[...FlatArr<First>, ...FlatArr<Rest>] :`
I haven't tried supporting a depth param, but I suspect it's possible.
That was... non-trivial.
export async function promiseAll<T extends Record<string, Promise<any>>>(promises: T): Promise<{ [K in keyof T]: Awaited<T[K]> }> {
const keys = Object.keys(promises) as Array<keyof T>;
const result = await Promise.all(keys.map(key => promises[key]));
return Object.fromEntries(result.map((value, i) => [keys[i], value])) as { [K in keyof T]: Awaited<T[K]> }; function flat([head, ...tail]) {
return Array.isArray(head)
? [...flat(head), ...flat(tail)]
: [head, ...flat(tail)]
}
...in TS syntax.I don’t think that means it has a steep learning curve. It just means the basics suffice for a ton of TypeScript deployments. Which I personally don’t see as the end of the world.
While I aspire to Library TS levels of skill, I am really only a bit past App TS myself.
On that note I've been meaning to the the Type-Level Typescript course [0]. Has anyone taken it?
As someone who knows slightly more than the basics, and enough to know about the advanced stuff that I don't know about, this is the correct place to stop.
I would much rather restructure my javascript than do typescript gymnastics to fit it into the type system.
If you're purely writing Typescript then you mostly don't need it.
For example, I don't ever see anyone using `dynamic` or `object` in C#, but I will often see less skilled developers using `any` and `// @ts-ignore` in TypeScript at every possible opportunity even if it's making their development experience categorically worse.
For these developers, the `type` keyword is totally unknown. They don't know how to make a type, or what `Omit` is, or how to extend a type. Hell, they usually don't even know what a union is. Or generics.
I sometimes think that in trying to just be a superset of JavaScript, and it being constantly advertised as so, TypeScript does not/did not get taken seriously enough as a standalone language because it's far too simple to just slot sloppy JavaScript into TypeScript. TypeScript seems a lot better now of having a more sane tsconfig.json, but it still isn't strict enough by default.
This is a strong contrast with other languages that compile to JavaScript, like https://rescript-lang.org/ which has an example of pattern matching right there on the home page.
Which brings me onto another aspect I don't really like about TypeScript; it's constantly own-goaling itself because of it's "we don't add anything except syntax and types" philosophy. I don't think TypeScript will ever get pattern matching as a result, which is absurd, because it has unions.
I think you're confusing things that aren't even comparable. The primary reason TypeScript developers use the likes of `any` is because a) TypeScript focuses on adding support for static type checking on a language that does not support it instead of actually defining the underlying types, b) TypeScript developers mostly focus on onboarding and integrating TypeScript onto projects and components that don't support it, b) TypeScript developers are paid to deliver working projects, not vague and arbitrary type correctness goals. Hence TypeScript developers tend to use `any` in third party components, add user-defined type guards to introduce typing in critical areas, and iterate over type definitions when time allows.
match (x) {
"bob": ...,
string: ...,
() => Promise<void>: ...,
() => Promise<string>: ...,
}
with exhaustiveness checking for it to be truly useful.I have bad news for you
I'm aware that type theory is a field in and of itself, with a lot of history and breadth, but do developers really need deep levels of type flexibility for a language to be useful and for the compiler to be helpful?
I think TypeScript encourages "overtyping" to the detriment of legibility and comprehension, even though it is technically gradually typed. Because it is so advanced and Turing complete itself, a lot of brain cycles and discussion is spent on implementing and understanding type definitions. And you're definitely right that it being verbose also doesn't help.
So it's always a bittersweet experience using it. On one hand it's great that we have mostly moved on from dynamically typed JavaScript, but on the other, I wish we had settled on a saner preprocessor / compiler / type system.
My point was more related to the level of expressiveness required of a type system in order to allow a programmer to produce reliable code without getting in their way. I think TypeScript leans more towards cumbersome than useful.
For example, I'm more familiar with Go's type system, which is on the other side of that scale. It is certainly much less expressive and powerful than TypeScript, and I have found it frustrating and limiting in many ways, but in most day-to-day scenarios it's reasonably adequate. Are Go programs inherently worse off than TypeScript programs? Does a Go programmer have a worse experience overall? I would say: no.
https://www.google.com/search?q=site%3Ahttps%3A%2F%2Fwww.typ...
keyof typeof[number] ? uppercase (myNum)
On the other hand, there isn't much Omit, readonly, mutable in existing code bases, so devs have nowhere to learn but documentation.
Then the ground shifts again and –what should be basic stuff – enums are banned, because erasableSyntaxOnly makes life so much easier.
Yes, precisely. OP is also completely oblivious to the fact that TypeScript is designed to help developers gradually onboard legacy JavaScript projects and components, which definitely don't require arcane and convoluted type definitions to add value.
There’s a lot you can do in TypeScript. But you don’t have to do it. And TS existed successfully a long time without those features.
Also you can so easily go overboard with TS and design all sorts of crazy types and abstractions based on those types that become a net negative in your codebase.
However it does feel really damn nice to have it catch errors and give you great autocomplete and refactoring tooling.
That's not a TypeScript issue, it's a code quality issue and a skill issue. Anyone can put together an unintelligible mess in any language.
If you type some state as:
isLoading: boolean
result: Foo
hasError: boolean
errorMessage: string | null
then you're creating a giant mess of a soup where the state of your program could have a result, be loading and an error at the same time. If you could recognise that the state of your program is a sum of possible states (loading | success | error), and not their product as the type above you could highly simplify your code, add more invariants and reduce the number of bugs.And that is a very simple and basic example, you can go *much* further, as in encoding that some type isn't merely a number through branded types, but a special type of number, be it a positive number between 2 and 200 or, being $ or celsius and avoiding again and entire class of bugs by treating everybody just as an integer or float.
class LoadingState extends State {}
class ResultState extends State {}
class ErrorState extends State {}
const state: State = new LoadingState
Generally it's a bad pattern to have dependant fields like your example, but you don't need TS to solve it.What’s the point of this level of autism when you still have to add run time checks?
I think you're both exaggerating your blanket accusations of incompetence and confusing learning curve with mastering extremely niche techniques akin to language gotchas.
Maybe they're smart, but the even smarter dev would avoid unnecessary complexity in the first place.
Frankly, I prefer it that way. A lot of the advance stuff doesn’t actually enable any new functionality. It only shortens the code paths for implementing.
Out of curiosity - what do you think is a satisfactory answer here?
My answer would vary wildly based upon more details, but at the most basic all I can think you could guarantee is Array<unknown> => Array<unknown>?
IRL I'd be happy with someone at least searching for a definition and trying to learn from it.
I've asked this question multiple times as implementing array flatten used to be our go to ice breaker question, and many devs had no issues reasoning and finding an okay type definition.
Rich Hickey in 10 Years of Clojure & Maybe Not then the Value of Values - lays this out - though not meant at typescript but static types in general.
the thing most people don't have proper Javascript fundamentals.
Function signatures: JSDoc works
Most types - use Maps | Arrays
if a value doesn't exist in a map we can ignore it. There's also the safe navigation operator.
Instead of mutable objects - there's ways around this too. Negating types again.
Claiming that lack of static type checking is a non-existent problem is quite a bold claim. Care to offer some details to substantiate your claim?
In my experience, here is summary of when you might want to use the various type features:
- Using the "as" keyword tries to coerce/cast an expression to be of some type. This is the least safe, since it overrides proper type checking, at least to some extent. However, in many cases it still does some level of type checking, and it is sometimes necessary if you know something the type checker is unable to prove.
- Declaring an expression to be of some type before initializing it. This is the strictest, and thus most safe, but sometimes it is inconvenient. You might want types to be inferred, which is a really useful thing sometimes, e.g., in a fluent interface when each step constrains types in additional ways.
- The satisfies keyword bridges the gap between the above two: you want to assert/check that the expression is assignable to a certain type (which can be as loose or strict as you want it), whilst still retaining the original type that is inferred for the expression. Unlike "as", you are not overriding the type system. And you are also not actually declaring a type for the expression. I have found this very useful on numerous occasions.
Having said that, there is weird (new?) behavior of the satisfies keyword where appending it to an expressions can cause the the expression itself to fail type-checking internally, where it would otherwise be fine.
This is strange, the basic premise of satisfies is to check if an expression satisfies a type. If there is a type violation at all, it should be at the expression/type boundary, not inside the expression.
It's making it less useful for me.
I find the base interfaces easier to read at a glance than derived types, especially in an editor’s hover view.
Though, nullable fields might get weird, iirc.
Replace "TypeScript" with "C++" and the same can be said.
It is one of the worst languages ever designed and already built on top of a sloppy foundation (Javascript) compared to Go.
The language encourages escape hatches and tons of flexibility on how it checks its types and creates the risk of inconsistency to engineers on which rules to adopt and there is always one engineer that will disagree with some settings and argue to turn on/off a rule to defeat the purpose of the language.
At this stage, its no better than C++ but significantly slower, and I've seen the same mistakes (enums, allowing "as XYZ" casting, etc) in C++ creeping into TypeScript.
Even the entire language parser and type checker is being rewritten in Go. [0]
[0] https://devblogs.microsoft.com/typescript/typescript-native-...
The reason it is being rewritten in Go is so the compiler can be run at native speeds which is a good thing. Otherwise the only runtime we have available is NodeJS which has its fair share of problems. You can go far with TS with just interface definitions and some generics peppered in for common utilities. The places where all the type gymnastics is necessary are cases I frankly havent encountered in the usual course of development.
export GOOS=js
export GOARCH=wasmconst x: Thetype = ....
I am not keen on as const either. Just program to interfaces. It is a better way to think IMO.
type Current = {
kind: "ac" | "dc";
amps: number;
}
type Dc = {
kind: "dc";
amps: number;
}
const ac: Current = {
kind: "ac",
amps: 10000000,
}
const handleDc = (thing: Dc) => {}
const badConvert = (c: Current) => ({...c, kind: "dc"});
/**
* Argument of type '{ kind: string; amps: number; }' is not assignable to parameter of type 'Dc'.
Types of property 'kind' are incompatible.
Type 'string' is not assignable to type '"dc"'.(2345)
*/
handleDc(badConvert(ac));
const goodConvert = (c: Current) => ({
...c, kind: "dc",
} satisfies Dc);
handleDc(goodConvert(ac));
/**
* Object literal may only specify known properties, and 'bar' does not exist in type 'Dc'.
*/
const badConvert2 = (c: Current) => ({
...c, kind: "dc", bar: "qwerty"
} satisfies Dc);The compiler isn't complaining because the conversion isn't valid, it's complaining because it doesn't know that the string "dc" should be narrowed down to a literal type, and so it's kept it as broad as possible. Using `satisfies` lets it understand that it needs to do narrowing here.
In fairness I don't think this is the best case for `satisfies`, and some return type annotations would probably work a lot better here, and be clearer to read.
const c: string = 'c';
This will be of type string instead of type 'c'. This is a barebones example and it already breaks support for template literal types. Imagine how much better `satisfies` is for complex union types.
edit: perhaps the advantage only comes into play for mutable values, where you want a narrower type than default, but not that narrow. Indeed, this is covered in the article, but CTRL+F "as const" doesn't work on the page for whatever reason, so I missed it.
1. Enforce that a value adheres to a specific type
2. But, doesn't cause the value to be cast to that type.
For example, if you have a Rect type like:
type Rect = { w: number, h: number }
You might want to enforce that some value satisfies Rect properties... But also allow it to have others. For example: const a = { x: 0, y: 0, w: 5, h: 5 };
If you wrote it as: const a: Rect = // ...
TypeScript wouldn't allow you to also give it x and y properties. And if you did: as Rect
at the end of the line, TypeScript would allow the x, y properties, but would immediately lose track of them and not allow you to use them later, because you cast it to the Rect type which lacks those properties. You could write an extra utility type: type Location = { x: number, y: number };
const a: Location & Rect = // ...
But that can get quite verbose as you add more fields. And besides: in this example, all we actually are trying to enforce is that the object is a Rect — why do we also have to enforce other things at the same time? Usually TS allows type inference for fields, but here, as soon as you start trying to enforce one kind of shape, suddenly type inference breaks for every other field.The satisfies keyword does what you want in this case: it enforces the object conforms to the type, without casting it to the type.
const a = { x: 0, y: 0, w: 5, h: 5 } satisfies Rect;
// a.x works
Then if someone edits the code to: const a = { x: 0, y: 0, width: 5, height: 5 } satisfies Rect;
TypeScript will throw an error, since it no longer satisfies the Rect type (which wants h and w, not height and width).How does this work,
function coolPeopleOnly(person: Person & { isCool: true }) {
// only cool people can enter here
}
const person = {
name: "Jerred",
isCool: true,
} satisfies Person;
coolPeopleOnly(person);
Since- person isn't const, so person.isCool could be mutated
- coolPeopleOnly requires that it's input mean not only Person, but isCool = true.
(You could mutate it to `isCool: false` later, but then TypeScript would complain because `isCool: false` is different to `isCool: true`. When that happens isn't always obvious, TypeScript uses a bunch of heuristics to decide when to narrow a type down to the literal value (e.g. `true` or `"Jerred"`), vs when to keep it as the more general type (e.g. `boolean` or `string`).)
What `satisfies` is doing here is adding an extra note to the compiler that says "don't change the type of `person` at all, keep it how it is, _but_ also raise an error if that type doesn't match this other type".
(This is only partially true, I believe `satisfies` does affect the heuristics I mentioned above, in that Typescript treats it a little bit like `as const` and narrows types down to their smallest value. But I forget the details of exactly how that works.)
So the `coolPeopleOnly` check will pass because the `person` literal has all the right attributes, but also we'll get an error on the literal itself if we forget an attribute that's necessary for the `Person` type.
One example is that we have a TS library for a JSON-RPC server that is horribly complex on the server side, returning different shapes of output based on input params. I don't think it can be typed with OpenAPI etc, but it can be with Typescript method overloads.
But then instead of writing unit tests that either coerce or mock the server into returning each shape, we can write typetests like this to make sure our type juggling provides the exact right types to developers:
const rpc = null as unknown as Rpc<SomeApi>
const result = await rpc.someApi(input).send()
result satisfies {
value: {
nestedFieldForThisInput: number
}
}
```The tradeoff is slightly longer compile times for the library since all this is checked at build time, but it provides a lot of flexibility for testing overloads and utility types in isolation.
Typescript in a nutshell. That said, satisfies is a good keyword!
EDIT: I dug through the codebase and determined that it's using Shiki and TwoSlash for the syntax highlighting and tooltips.
However, the object can still be mutated via other references to it. TypeScript is full of holes like this in the type system - the problem is that they are trying to bolt types and immutability onto a hot mess that is JS data model while preserving backwards compatibility.
I want an object of ‘LayerConfig’ elements where each key is the name of a possible layer. Without ‘satisfies’ I have to name every layer twice in my config. But with it, I can’t have optional properties (eg. Half the layers are fine with the default values for some properties).
The best I’ve found is a hack that uses a function. But this whole thing where my key literals widen into “string” is a constant annoyance to otherwise very elegant code.
> Why is the name of person1 of type string and not the literal "Jerred"? Because the object could be mutated to contain any other string.
Not really, if you declare {name: "Jerred" as const}, it's still mutable. Typescript just decided that given certain primitive-like types like strings, it's preferrable to infer string rather than as constant.
Satisfies offers the opposite AS A MOSTLY ORTHOGONAL design decision. It's a happy byproduct that the type inference's behavior is changed.
And this is relevant because it affects technically important situations like deeply nested values NOT being narrowed, but it's also just not a good mental model for what it's supposed to do.
People should assume that given a type literal, that it just infers the widest typing. Incidental behavior that arises from using 'as const', or 'satisfies' should follow it's semantic purpose. If you want specific typing, just build the type - don't use hacks.
Satisfies is useful because sometimes you have something with some typing (often as const for something like utils), that you also need to make sure satisfies some other typing - almost as a constraint.
Would not surprise me if ts team released a keyword that did type inference with narrowest (like as const, but without the readonly).
Don't get me started on how this is so unnecessary on the browser (so the utility on this kind of stuff is actually for library development; maybe).
Am I the only one that thinks that Typescript waste your time on minutia like this?
For example, a naive engineer might think, ah, databases have this oFFSET clause, good, I'll use, unaware that is a foot gun for real world performance.
Or they may think the DELETE operation on DBs is a normal thing, unaware that in most cases it should NOT be used at all.
Or they might think loops are idiomatic, unaware that when you are writing large software you should and can probably almost eliminate loops (unless you are using a DSL like SQL extensions, config languages, etc)
Or they may be unaware of the thorny issues around queues (or even why they might be necessary in the first place) and concurrent access to data.
Or they might not understand why the dogma of separating content and presentation is nonsensical in many situations.
Etc.
Also, Angular dev spotted :)
You might be interested in reading PG's treatise on "the blub paradox".