Type Predicates Solve This Common TypeScript Error

Поделиться
HTML-код
  • Опубликовано: 14 июн 2024
  • TypeScript Simplified Course: courses.webdevsimplified.com/...
    Type predicates are an interesting feature in TypeScript since they cover a very niche use case that can cause type errors if you are not aware of this solution.
    📚 Materials/References:
    TypeScript Simplified Course: courses.webdevsimplified.com/...
    🌎 Find Me Here:
    My Blog: blog.webdevsimplified.com
    My Courses: courses.webdevsimplified.com
    Patreon: / webdevsimplified
    Twitter: / devsimplified
    Discord: / discord
    GitHub: github.com/WebDevSimplified
    CodePen: codepen.io/WebDevSimplified
    ⏱️ Timestamps:
    00:00 - Introduction
    00:17 - The Problem
    02:12 - Type Predicate Basics
    03:15 - Type Predicate Problems
    #TypeScript #WDS #TypePredicate

Комментарии • 128

  • @bvx89
    @bvx89 5 месяцев назад +52

    In all my TS project I add this utility function:
    function isDefined(value?: T) value is T {
    return value !== null && value !== undefined;
    }
    It's very useful when I have a list of items where some of those items might be undefined:
    list.filter(isDefined).forEach(item => {
    // `item` is now correctly inferred to not be undefined or null
    })

    • @big-jo89
      @big-jo89 5 месяцев назад +5

      nice one, and correct me if I'm wrong, but I think you can just do :
      return value != null;
      this way it should check for the null and undefined values

    • @bvx89
      @bvx89 5 месяцев назад +14

      @@big-jo89 We have a linting rule to always use tripple equals, so that's why I check for both.

    • @big-jo89
      @big-jo89 5 месяцев назад

      @@bvx89 oh, I see

    • @piaIy
      @piaIy 5 месяцев назад +3

      It doesn't filter null and marking the parameter as optional is misleading. The correct type would be `value: T | null | undefined`.

    • @bvx89
      @bvx89 5 месяцев назад

      @@piaIy True, I should change that. The point still stand though.

  • @gameraz1990
    @gameraz1990 5 месяцев назад +13

    I happened to run into this very same issue just a week ago, and learned what you're teaching, and made great use of it.
    Now you teach it with a sweet simple example, further cementing my knowledge of the subject.
    Great job man!

  • @kaushikchopra3149
    @kaushikchopra3149 5 месяцев назад +4

    This man really simplifies everything in web dev. Great content. Just love it. ❤️

  • @theisoj
    @theisoj 5 месяцев назад

    Great video! Thanks Kyle as always 💯

  • @Niksorus
    @Niksorus 5 месяцев назад +8

    Afaik, this is actually called a type guard. A very important notion indeed 😊

    • @dstutz
      @dstutz 5 месяцев назад +3

      The "person is Employee" bit (the return type specifically) is called a type predicate

  • @jx4172
    @jx4172 5 месяцев назад

    This is excellent! Thankyou! I didn’t know about this one ❤

  • @Duckception
    @Duckception 5 месяцев назад

    Brilliant. I've been wondering about this!

  • @anibalsancheznuma3133
    @anibalsancheznuma3133 5 месяцев назад

    Thanks, man, very interesting as usual.

  • @benjamin-lieb
    @benjamin-lieb День назад

    The TS website doesn't do a good job explaining this, but you did! Thanks!

  •  5 месяцев назад

    Great!! Just welcome again!!

  • @_nikeee
    @_nikeee 5 месяцев назад

    User-defined type assertion functions using `asserts` would be a great addition to this video, since it can build upon this predicate function.

  • @ThaiNguyen-gg8xj
    @ThaiNguyen-gg8xj 5 месяцев назад

    Your video about the type predicates is more worth thousand times than the official document.

  • @beats4all914
    @beats4all914 3 месяца назад

    this TS tips are amazing

  • @el.bromas
    @el.bromas 5 месяцев назад

    Amazing! Bro

  • @mohammadkhayata2042
    @mohammadkhayata2042 5 месяцев назад

    you saved my life !

  • @lasindunuwanga5292
    @lasindunuwanga5292 5 месяцев назад

    Thanks

  • @olegdeviatko4956
    @olegdeviatko4956 5 месяцев назад

    Great!

  • @ryzott
    @ryzott 5 месяцев назад +1

    How about narrowing using switch case ? how should I return the exact type for multiple cases ?

  • @macigli
    @macigli 5 месяцев назад +3

    That's a really cool feature but the OOP dev inside me want's to scream 😂

    • @gonzo191
      @gonzo191 5 месяцев назад +1

      I'm watching in absolute horror

    • @eminvesting
      @eminvesting 5 месяцев назад

      Why? If I may

    • @semosancus5506
      @semosancus5506 5 месяцев назад +1

      Yeah I agree. I'm just learning javascript and typescript, but come from Java / Kotlin background, and I thought "what in the heck ???" Somehow this magic code infers a type when the boolean function returns true and infers some other type when it's false??? So bizarre. Typescript kind of checkmated themselves with their type inference rules.

  • @drprdcts
    @drprdcts 5 месяцев назад

    Can you also cover type assertions? (asserts person is User)

  • @snake1625b
    @snake1625b 5 месяцев назад

    Handy when you have nested union types

  • @yassinmoussaoui3323
    @yassinmoussaoui3323 5 месяцев назад +2

    why not an enum with user and employee?

  • @mmanomad
    @mmanomad 5 месяцев назад

    I'd love to see some videos on Deno's fullstack Fresh framework! I think it's a great alternative to Node.js frameworks such as React and Next.js.

  • @benjaminjeschke
    @benjaminjeschke 5 месяцев назад +1

    I dont understand. isEmployee() returns a boolean. So I would write: isEmployee(person:User| Employee): boolean. Where do I write the boolean return type in your example ?

  • @dazecm
    @dazecm 5 месяцев назад

    I’m still learning typescript but I’m wondering if using interface instead of type for User and then using type inheritance for Employee would also solve this issue?

  • @MrJettann
    @MrJettann 5 месяцев назад

    But how to use it with 3 or more types? Is there a way of doing that clean?

  • @JediMediator
    @JediMediator 5 месяцев назад +1

    Isn't this kind of getting into runtime type checking? For that I prefer to just use Zod.

  • @aless.c064
    @aless.c064 5 месяцев назад +3

    What about using instanceof?

    • @martijn3151
      @martijn3151 5 месяцев назад

      The array doesn’t contain instances, just objects with some fields.

  • @Thassalocracy
    @Thassalocracy 5 месяцев назад +3

    I think object design patterns also play a role here. The shape of the data object should be consistent for all persons. If the person is merely a User then he/she should still have an email key of "null". Then assign NonNullable to Employee's email type.
    I don't like using "as" or "is" as it could cause unintended bugs like shown in the video.

    • @stevezelaznik5872
      @stevezelaznik5872 5 месяцев назад

      If I’m using a 3rd party API typescript can’t do anything about that. All I can do is cast it in Typescript and provide a runtime check that the API response is in the shape I expect

    • @birthdayzrock1426
      @birthdayzrock1426 Месяц назад

      Zod may help

  • @nomadshiba
    @nomadshiba 5 месяцев назад +1

    You can make the argument type only User btw

  • @sandrinjoy
    @sandrinjoy 5 месяцев назад

    how does this help, if the helper function is some common util functions that's used for several purposes?

    • @gidmanone
      @gidmanone 5 месяцев назад +2

      well, it means you will need to 😃create 50 of it. typescript is a mess and overly complicated even for simple things

  • @orangeblossom9968
    @orangeblossom9968 5 месяцев назад +1

    can anyone please explain 3:38: why is it inferred that pesron will be of type never? Isn't it supposed to be Employee by what's returned from the guard function?

    • @Pacvalham
      @Pacvalham 5 месяцев назад +3

      isEmployee takes a User or Employee, and Employee extends User (0:20), so if it is an Employee, it is a User. If it is not a User, it is also not an Employee, but that was the declared type in the param, so this condition would Never be reached.

    • @orangeblossom9968
      @orangeblossom9968 5 месяцев назад

      @@Pacvalham thank you!

  • @aurelian3401
    @aurelian3401 5 месяцев назад +2

    Hello, what is the use of Typescript, since the browser uses JavaScript?

    • @eresy.5968
      @eresy.5968 5 месяцев назад +1

      To check when coding if you're doing mistakes

    • @yoni532s9M5w
      @yoni532s9M5w 5 месяцев назад

      It adds types. Better than plain js in any way possible.

    • @markokafor7432
      @markokafor7432 5 месяцев назад

      Typescript is for the developer's use

  • @nasirmuslih4128
    @nasirmuslih4128 5 месяцев назад

    Please i have a little question with HTML and CSS how can i send it so that yiu help me with ut please if possible

  • @henrikholst7490
    @henrikholst7490 5 месяцев назад

    I failed to see why I would extract "is Employee" into a function called "isEmployee"?

  • @mahdijafaree5332
    @mahdijafaree5332 5 месяцев назад

    also array.filter is not smart enoght so you need to use type guards.

  • @uncleelder4922
    @uncleelder4922 5 месяцев назад

    Why should I need an advanced course in typescript to write code that says a person is not necessarily a user? There has to be a better way.

  • @fabio-nettis
    @fabio-nettis 5 месяцев назад +6

    Syntactically this looks horrible.

  • @aeronwolfe7072
    @aeronwolfe7072 5 месяцев назад +1

    'the hair' strikes again! :) i didn't know this! good video!

  • @Caldaron
    @Caldaron 5 месяцев назад +1

    even worse: rename email and "email" in person doesn't get refactored...

  • @PopHeige
    @PopHeige 5 месяцев назад +1

    This is cool and all but I think its bad practice to make ”smart” code which in a couple of years will be suoer hard to read and understand.

  • @coc1841
    @coc1841 5 месяцев назад +1

    Ducks can swim, just sayin'

  • @kasratabrizi2839
    @kasratabrizi2839 5 месяцев назад

    I really like this video and I totally get the solution but at the same time, it goes to show you why some people hate Typescript. In this small example, you have to add all of these stuff, just to make things work which shows that FE development is going in the wrong direction. I really believe we as a community need to come up with a better solution (maybe even use the help of AI), to simplify all of these stuff. Otherwise, we need to hire full time Typescript developers just to be implement and to find and fix bugs. One of my colleagues is working at React project with Typescript and he decided to remove typescript completely as it was making everything way more complex than it should have been.

  • @chrisbirkenmaier2277
    @chrisbirkenmaier2277 5 месяцев назад

    Typescript doesn't really make it easy to write clean, modular code. The more you pull out code into own modules and functions (instead of writing linear inline code), the more you have to handle types manually and help typescript infer the correct types, making the whole experience worse and error-prone.

  • @Spadeads
    @Spadeads 5 месяцев назад

    Basically looks like a little hack. I love it anyway, idk why

  • @gmoniava
    @gmoniava 4 месяца назад

    Can't see code from mobile

  • @keremardicli4013
    @keremardicli4013 5 месяцев назад +9

    I am afraid typescript is getting out of control and this is why big projects start to leave it. İnstead of focusing main codebase, you try to solve type problems most of the time. It feels like playing hide and seek with types and js

    • @doobtom271
      @doobtom271 5 месяцев назад +1

      name a big project leaving ts back to js?

    • @keremardicli4013
      @keremardicli4013 5 месяцев назад

      @@doobtom271 svelte

    • @XTANCE
      @XTANCE 5 месяцев назад

      "Type problems" - typing your code is not a problem as it saves a lot of time later when you need to debug.
      I am not sure how a big project would work without TS or at least JSDoc.

  • @xxXAsuraXxx
    @xxXAsuraXxx 5 месяцев назад +2

    Soon, no developer problems only AI problems

  • @sanan4li
    @sanan4li 5 месяцев назад +2

    This is not advanced typescript. This is code pollution. Imagine someone else has to understand all this shit with a bigger example than this.

  • @HealmaTech
    @HealmaTech 5 месяцев назад

    Typescript is becoming weird everyday😢

  • @user-su4rq2dt2r
    @user-su4rq2dt2r 5 месяцев назад +2

    а по русски?

    • @gidmanone
      @gidmanone 5 месяцев назад +1

      sorry никто не по русский говорить😃

  • @dayachettri5157
    @dayachettri5157 5 месяцев назад

    Learn rust

  • @walkingin6375
    @walkingin6375 5 месяцев назад

    //@typescript ignore

  • @uncleelder4922
    @uncleelder4922 5 месяцев назад

    The real problem here is not Typescript. The real problem stems from the object-oriented programming paradigm in general. That's why the problem can't truly be fixed with the Typescript language. In fact, several languages have come up with clever but futile ways to fix this type of problem, but the only real solution is to avoid objects (aka, types) in general.

  • @7heMech
    @7heMech 5 месяцев назад +145

    Not using typescript solves all typescript problems.

    • @otis3744
      @otis3744 5 месяцев назад +9

      a lot developers realise this and it changes their lives

    • @arshiagholami7611
      @arshiagholami7611 5 месяцев назад +75

      Good luck writing production ready apps and libraries. you probably have to waste half your time writing tests that can be solved by just using TS.

    • @bryson2662
      @bryson2662 5 месяцев назад +44

      No programming, no errors.

    • @ts3798
      @ts3798 5 месяцев назад +45

      Good luck building anything more complicated than a todo list

    • @arshiagholami7611
      @arshiagholami7611 5 месяцев назад +14

      @@otis3744 you sound like a dev that documents each of their function params with JS Doc

  • @drelroy
    @drelroy 5 месяцев назад +1

    Again, without semicolons...

  • @ElPolemista
    @ElPolemista 5 месяцев назад

    When coder works for the sake of the language, what a waste of time

  • @ashique12009
    @ashique12009 5 месяцев назад

    You're good enough but too fast, too. Take a rest and talk. People need to grab too what you're saying. Thanks. 👍

  • @CottidaeSEA
    @CottidaeSEA 5 месяцев назад

    This is why duck typing sucks and is why I will never like TypeScript.

  • @user-pq8zg6rx8c
    @user-pq8zg6rx8c 5 месяцев назад

    Hi there, devs! I have a question that am struggling at for about a week. I know it doesn’t reference the video topic, but I appreciate all help you can give.
    I am doing react(vite) Frontend on my job. There is a task to implement Notifications in browser(even when it’s in foreground). So I decided to use service worker for that. But then I run into issue: I subscribe for event source, that sends me messages. It requires authentication token, so I use @microsoft/fetch-event-source to specify token. So I can’t simply import that library in worker since it doesn’t support import. What should I do? Maybe there is any better solution for handling notifications without loading main thread?

  • @joanstacco12
    @joanstacco12 5 месяцев назад +1

    isnt better use instanceof? if (person intanceof Employee){ persona.email}

    • @thebeastsclips
      @thebeastsclips 5 месяцев назад

      This is type script and the typescript-eslint will still throw an error if you use that.