Most TS devs don't understand 'satisfies'
ฝัง
- เผยแพร่เมื่อ 28 มิ.ย. 2024
- 00:00 Intro
00:33 Variable annotations
00:53 What satisfies does
02:01 When satisfies is GOOD
02:39 When variable annotations are BAD
03:41 Outro
New Tutorial: www.totaltypescript.com/tutor...
Become a TypeScript Wizard with my free beginners TypeScript Course:
www.totaltypescript.com/tutor...
Follow Matt on Twitter
/ mattpocockuk
Join the Discord:
mattpocock.com/discord - วิทยาศาสตร์และเทคโนโลยี
I wish you added that 'satisfies' can be combined with 'as const'. It is obvious, but still nice to mention i think
It's not that obvious, it was only recently allowed 😂 It should have worked from the start though, clearly.
afaik it basically already does that, other than the part where `as const` also makes stuff readonly, which usually just adds additional confusion
What does the combination do?
@@NikiHerl there are some situations where you want to infer the type as closely as you can, while ensuring the object you create follows some other type. That is where i use it
You have made such an impact on the TS community, and enriched us all with your courses, articles and TH-cam content. Thank you so much!! I wish us all a wonderful new TypeScript year 🎉
clear
Before "satisfies" you had to make a choice whether you want something to adhere to a type OR be of the more specific type. With "satisfies" you get both.
You could've done both, but in a very odd manner.
typing a word like "satisfies" is satisfying
Happy new year, Matt. Thanks a lot for your work, and I have to say that satifies still eludes me, but this video provided a nice use case.
Happy new year matt! the typescript 🐐
All the best for 2024 Matt, hope you keep making awesome content for all the wizards!
Thank you for this clear explanation. Please continue making such videos focusing on a specific topic only.
You're a champ, Matt. Thanks!
`satisfies Partial` phenomenally useful
This video has been very satisfying, thanks Matt
I've been waiting for more satisfies videos!!
Great explanation Matt! Thanks. Will try to narrow my types further where possible to get more autocompletion.
Fantastic content once more, thanks Matt! I appreciate the single-topic video format as well. I'm also looking forward to the book release, especially since the premium TT courses are a bit too expensive for me to purchase at the moment.
Brilliant explanation, thanks!
I started using satisfies more because of its “const” value as well. This is such a good tip. Awesome video as always!
Happy holidays Matt
I’m trying to step up my TS game and your videos are really helping me!
Oh wow, great stuff! Nice explanation and use case!
The best explanation regarding satisties I have encountered so far!
You don't know how much you helped me with this. I didn't know about this `satisfies` keyword and I had to write duplicate code to get object constraint with autocompletion as typing out `Record` on variable I always loose keys autocompletion.
i needed this, thank u brother
Love your work!
Thanks for this explanation! In essence, this is like writing:
const name: extends string = "sam";
Which is something I've always wanted to be able to do.
I would have loved you to show off satisfies's power a little more at the end by showing one of those massive config objects! It can get really useful when combined with discriminated unions for different types of config options as well
I found it useful sometimes when asserting string literals, say I have something like `type State = 'Idle' | 'Succes' | 'Error'`, then in another place in the code I might have `'Idle' satisfies State`, which will assure the type error is caught if I ever change the string literal
There are better ways to handle this typically but in some situations it can be pretty useful
Seems like ages since you last popped up in my feed and said "what's up wizards".... welcome back. :)
Can you describe how satisfies is different from "as const" which also seems to narrow the type. Thanks and happy new year :)
as const makes a value deeply readonly
satisfies checks that a value satisfies a type
And sometimes it's nice to use both at once.
So if you know that your objects field are never going to be mutated then use as const. If you're adding new fields then use colon. If your mutating existing fields then use satisfies?
Being unfamiliar with being able to satisfy seems to be a common issue with programmers.
primeagen have 4 kinds lol
This video satisfies any TypeScript developer. Thumbs up for you Matt.
hi Matt, totally love ur content! im curious how did you had those `// ^? (property) ...`?
thank you!
It would be great if they had some way of type propagation. Take a look on an issue 54976, please.
Nice one!
excelent video
Would be cool to see TS tricks for each framework like SvelteKit
really good topic
instead of the variable annotation in the first example, it is possible to also just use `as` - although this can cause other issues
Thanks
Recently I discovered using satisfies with generic types also seems to narrow the type parameters if they would otherwise be inferred as any.
Looking forward to that book Matt. Do you plan on pushing out physical copies or will it just be digital?
Physical! Signing with a publisher.
@@mattpocockuk hell yeah that's what I wanted to hear
You’re great 👍
This is very useful, 🎉🎉
What maybe the difference from as MyType ?
as MyType acts like ':', but also allows for illegal stuff. It's a way of lying to TS.
The satisfies keyword was one of the things i was missing the most in typescript
How `as const` plays into this? When to use one over the other or both at the same time?
Right now I'm using `as const` for my config and I have something like this:
```
const MY_NAMES = { A: 'a', B: 'b' } as const;
type MyNames = ValueOf;
const MY_CONFIG: Record = {
[MY_NAMES.A]: { id: 'a', name: 'a' },
[MY_NAMES.B]: { id: 'b', name: 'b' },
} as const;
```
Does it makes sense to use satisfy in that scenario? Is it providing any benefit?
One of the big issues I keep encountering with set value objects is if I want to declare a shape on an object or array, I can't also use as const. It loses those exact values. But using as const without setting the shape, it doesn't error if not all values of an enum are used. I wonder if satisfies could help here in some way
Absolutely!
{} as const satisfies MyType
is what you need.
You have some enum and want an array to have a single element per each enum value?
Take a look at srtackoverflow questions 59032886 and 58437445.
Never heard about this. Cool🤔
Good to know, actually. I feel like it should be used as a niche kind of thing more than regularly though. Inferred typing if you can!
Another thing about satisfies is that using it with well defined interfaces means you don't accidentally widen the type but also get type safety and errors at the correct place. If your config object is passed to a function that expects a Config type but the object does not satisfy Config type, it'll error at the call site, how've you really want it to tell you at the declaration site
The way I read this now, this is similar to as const, but with as const you are narrowing the entire thing as a value while this will narrow the types for you only ? I saw also another comment that satisfies can be mixed with as const, what are actual use cases were combining both is desired?
The title is true. Solidstart used it for its new RouteDefinition and I replaced it with :Routedefinition because I didn't understand it.
Is the "^?" comment to display the variable type an extension you're using?
It's like type validation for variable declaration.
Hmm ok. So it's almost like a slightly less strict `as const`. It lets you keep your type strictness (or not leaving it up to inferred), while still having devtool capabilities.
1:20 What is that extension that "translate" errors?
I guess it's "ts-error-translator", which is developed by Matt!
satisfies any
So with satisfies you just say the object has to satisfy the type declaration, like a template?
Hi, yes it works, but if we take type from object as typeof config, where we will have ab boolean, it can get an error: `Type boolean is not assignable to type false` (you can try to use it)
Could you elaborate?
@@mattpocockuk
```javascript
const initialState = {
isBoolean: false,
someText: 'text',
} satisfies Record;
type TInitialState = typeof initialState;
const state: TInitialState = initialState;
state.isBoolean = true;
state.someText = 'other text';
```
In my case something like than, but in the react, where we can use useReducer and later can't update state because boolean can't be as fasle
I think i didnt get the difference between omitting the satisfied keyword on your second example vs specifying it? You have intelisense on both options and type-safety - right?
Without "satisfies" it would be "{ wide: string; narrow: number }. Satisfies lets you make both of them "string | number".
The difference is that without satisfies, there's no type checking on the value itself. So I could add a boolean there without it erroring.
The difference is that when you insert keys/values, the keys/values can be only of that `satisfy` type you've inserted, meanwhile, if you omit the satisfies keyword, you can have any type as keys/values.
Edit: Hadn't refreshed the video, OP has responded.
Can you point out the difference when using as const?
as const makes a value deeply readonly.
satisfies ensures that a value matches a given type.
@@mattpocockuk Thanks! Huge fan of your work
If the type is known before hand, why would I use satisfies instead of something like this : { [key: "wide" | "narrow"]: string | number }
Note that in your version, both 'wide' and 'narrow' would be string | number.
And you'd have a duplication between your types and your runtime (of wide and narrow).
satisfies is really useful when you have MASSIVE config objects you need to make sure are the correct shape.
I wish this wasn't a totally different syntax from variable annotation, this is going to confuse the hell of out people not used to typescript
I feel like I can remember what satisfies does or I can remember what as const does, but I can't retain both at the same time.
I have a terrible memory, but I think another part of the problem is these keyword names seem arbitrary relative to their behavior. They may as well be a magic number.
Satisfies allow you to mutate fields, const you can't mutate
interesting, might be useful
hey matt, how do you get the type to show up in the comment?
Try the Twoslash extension for your IDE. I just installed Twoslash Query Comments for VS Code and it looks great.
thanks
Seems like you could use `satisfies T as T` to get the originally desired behavior too.
Yeah I still don't get it 😕
I am "satisfied" with your explanation
😀🔫
I don’t use JavaScript and I’m the most satisfied 😅
Your channel need some playlists to sort your content based on topics
I need to learn more about ts, but don't know what are you talking about in your videos from the title
So much of TS seems to be about wanting autocomplete options. It just seems very... backwards...
If this is the only use case, it seems pretty niche to the point of uselessness
Depends, if you've got a configuration as the uploader mentioned, and other developers will add stuff into it (you're not the only one, or even if you're the only one, you wanna limit yourself), you would want to limit stuff into being only of specific types.
thats basically whole typescript, majority is useless
as the name suggests
Of course I don't understand 'satisfies', it's literally the first time I see it, and only because of youtube recommendations.
Thanks for explaining! I’m still confused about the meaning of widening and narrowing though..
I'm a bit confused though. What is the difference between const config: {wide: string, narrow: number} = {wide: "100px", narrow: 0} and your example using satisfies?
For example, you mentioned that satisfies is good for keeping the type annotations narrow, while variable annotation is for keeping it wide, however, that would only apply for objects where the keys are not known beforehand if I understand it correctly. Your example with satisfies seems to already have predetermined keys so why would I use satisfies over my own example, or are they the same in this case?
If you have a large config object that you want to make sure is constrained to be a certain type, satisfies is great!
@@mattpocockuk I guess I need to dig in deeper. Satisfies might be better when you are working with an object of which the keys are not known yet and so in that case it might work if you use something like Record. But if you already know the keys and what types they accept, what would the difference be between?:
1. const config: { a: string, b: string | number } = {a: "example", b: 1}
2. const config = { a: "example", b: 1 } satisfies Record
@@Voidstroyer Good question!
The difference is one of ergonomics. In your example, every time you add a new key you need to update it in two places - the type and the value. With satisfies, you just update the value and you're good to go.
@@mattpocockuk Oh I see. That's a good point.
How do the “^?” comments work? Is that some sort of vscode extension? I have been looking for it for ages but couldn’t find it.
Apart from that, nice video!
Twoslash Query Comments extension for VS Code
... I don't even use typescript; why is this getting recommended to me, alongside _python_ of all languages??
Probably because you're engaging with it?
I still don’t really see the point of this. You can get inlay hints on members by not explicitly stating the type as record, too, and I suggest you often do intentionally let typescript determine the type for you.
i feel like languages that have guides for syntax and it is an actual problem should not exist. Programming should be programming, not spelling, syntax, punctuation or codestyle
Every day I feel more and more that TypeScript is a big workaround and messy language
weird , typescript became over-engineer javascript linter
First
Yes, because we have a life.
Longer is better. Not a fan of these st all tbh
TypeScript seems bloated. I use like 10% of what I learned about it in your course. We use Angular for our project.
It isn't bloated, it's really expressive and I use 100% of it, if you think about it, the language itself doesn't add even too much on top of js, but it allows you to express things that no other language can
Skill issue.
This can be said for any programming language.
A programming language containing features you don't use? Wow, it's almost as if the world doesn't center around you and programming languages are made for many different people.
Your statement only true with application project. For libraries and utils in which needs lots of generics and advance typed stuff, all those features you deemed unnecessary are very very needed.
Fuq typescript!!