The TypeScript feature I never use

preview_player
Показать описание
TypeScript gives us several ways to do type assertions, but they aren't all equal. Any time you're stepping over the TS compiler's choices, you might be creating a foot gun for later. Let's talk about why this is, and several ways to avoid it.

*Linked Mentioned in the Video*

*My Links*
Рекомендации по теме
Комментарии
Автор

for `findOrThrow`, a safer way to write the function would be `if (t === null) {...}` since we might be looking for something that resolves to 0.

Автор

I find it very hard to be able to escape `as`. For example fetching JSON from an API where you know the shape they are in, working with the dom and events (event.target), using libraries that are poorly typed (like the chromecast types on definitelytyped which are both incomplete and wrong).

pastenml
Автор

I also use your approach and try to avoid `!` or the `as` keyword as much as possible, but one thing that people normally forget to mention is, with the examples you gave (isMember, assertsMember, isNotNull) or type checking/narrowing is general, that you are introducing runtime behaviour to fix a compile time problem. That type checking/narrowing doesn't come for free and sometimes I see people checking deeply nested properties and such just to get to the type that satisfies TypeScript enough.

You are correct in that one normally relies on these checks when at the edge of the system, but even then, although I understand safe guarding against client code, I think that when you are in control of a specific end to end edge of the system, I would argue `!` and `as` to be a nice way to save some cycles!

Great vid btw! Keep at it!

Guergeiro
Автор

Thanks for your thoughts. Always love hearing the fundamental perspective of other developers.

StephenMoreira
Автор

You can cast an object (Perhaps even an array) using generics.
```
type Person = {
name: string,
age: number,
}

const person = <Person>{
name: 'John',
age: 47,
};
```

Personally, I like this syntax quite a lot however it's effectively the same as `person: Person`. unlike `as` which doesn't force said format.

Azoraqua
Автор

Another one of your videos that I’ll show to the team.

ness-ee
Автор

I couldn't help but notice the color of your ears change as the video progresses. On the other hand I really enjoyed the video and I think it is very helpful.

gordonfreimann
Автор

can you guys imagine the amount of hours this guy has put into typescript to get to where he is now? As a beginner myself, I feel like he's speaking chinese

ricko
Автор

`asserts arg is Type` is new to me. Very nice.

RobertKonigsberg
Автор

Another way to see the “as const” is to declare a literal

oscarcastillejo
Автор

Checked where I'm using it:
import/export { foo as bar };
[] as T[];
{} as T when {} is a valid instance of T;
Some situation with co/contra variance in higher order function overloading;
Some situation when composing multiple generic higher order functions and it is too difficult for TS to infer the correct (still generic) type.

Thanks to this video, I realized I no longer need some other instances of 'as' in my code and there is one more I can potentially remove by improving a type definition and allowing TS to generalize all argument types to a common type.

killymxi
Автор

I've found myself a few times needing to do `as unknown as SomethingElse` and that leaves a horrible smell in the room... but, at my current stage, I don't see any way around it.

edgeeffect
Автор

`As` soon `as`... (pun intended!) one needs to use .querySelector combined with other DOM methods they become friends with `as`. Every HTML element has typically an inheritance hierarchy of at least 3 levels: Node, Element, HTMLElement, and so on. Depending on where you need the result you might have to use `as` to achieve a proper coercion. As for `asserts something is Something` - I personally avoid these, for exactly the same reason you mention: there is never a 100% certainty, and if so - I would like to avoid throwing errors.

aram
Автор

Excellent video, thanks a lot!

Btw, it'd be great if you have the chance to add timestamps to your videos, it really helps a lot!

wtl
Автор

I use `as` in tests, when I don't want to pass all the fields of a type in a particular test. I never use `as` outside test (obviously, excluding the `as const`).
Also, that `isMember` function might lie to you in the future. Let's say, two weeks later, somebody adds field 'foo'. And you don't update the `isMember` function. In that case, the function wil lie. The problem is that both `as` and `is` are a programmer's promise that the they know better than the compiler.
In order to be 100% sure, you have to use a library like zod. The problem is, that it might be too heavy to be used in the browser

pawekoaczynski
Автор

Just use a general assertion function to assert it's not null. Then you get narrowing.

Declare function assert(x: unknown): asserts x;
assert(x != null)

This also doesn't address the common (anti)pattern of type widening assertions.

const myRef = ref(null as null | HtmlElement);

This is better to workaround with
const myRef = ref<HtmlElement | null>(null)

KirkWaiblinger
Автор

I find that `as` is sometimes necessary in certain generic functions or classes where it is 100% certain that something has to be a specific time, but the compiler can't work that out, so you have to tell it.

neilpadfield
Автор

Thanks. I 've been trying to figure out how to deal with a complicated union of types returned from a nuxt composable. I think these methods will help.

ThaRealIansanity
Автор

Me yolo swaging with "as unknown as T"

camotubi
Автор

Casting comes from 'C. It's not a runtime behavior. idk where you get that casting is a runtime behavior.

artistish
visit shbcf.ru