[Discussion] How to do the type casts? (`<Button> something` or `something as Button`)
akudev opened this issue · comments
In the last "UI5ers live" online session, feedback was that typecasting with as
is bad style and whether this can be fixed.
There are two syntax variants:
<Button> something
something as Button
The latter was introduced because the former does not work within JSX syntax. In UI5 JS code both could be used and they are functionally equivalent.
My initial search for style guides has led to:
- https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions:
- "Using one over the other is mostly a choice of preference"
- https://stackoverflow.com/questions/13204759/typescript-or-javascript-type-casting (the two answers with many upvotes):
- "If you are in a position to choose, just use the syntax that you feel more comfortable with. I personally prefer the as-syntax as it feels more fluent to read and write."
- You can cast like this ['as' way of casting] Or like this if you want to be compatible with tsx mode: [<> way]
- https://google.github.io/styleguide/tsguide.html: this official Google TypeScript style guide does not explicitly recommend a preferred syntax for casting, but the
as
-style casting is used all over the place, e.g. in:const mockBookService = ({get() { return mockBook; }} as any) as BookService;
- https://dev.to/ylerjen/typescript-cast-is-a-type-breaker-1jbh:
- [às
or
<...>`] - "The former being probably better (opinionated) as it can't be confused with the angle bracket notation for generic types."
- [às
- The TypeScript compiler code itself is written in TypeScript and as far as I see, it uses the
as
syntax for type casting, e.g. around https://github.com/microsoft/TypeScript/blob/main/src/compiler/core.ts#L770:return deduplicated as any as SortedReadonlyArray<T>;
compareStringsCaseSensitive as any as Comparer<T>
Overall, I was not able to find any evidence that casting with as
is generally considered "bad style". In contrary: if at all, as
seems to be slightly preferred.
Casting at all is of course something that should be better avoided, but cannot in all cases (as seen from the TypeScript compiler code itself), especially when there are existing APIs returning superclasses. The idea to make use of generics to ease this a little exists, but comes with drawbacks.
But the discussion is open for additional input.