#Generic vs return
8 messages · Page 1 of 1 (latest)
In the second you've explicitly set the generic, in the first TS has inferred the generic:
const element = document.querySelector(".first")!;
let elementA: HTMLInputElement = element;
// ^^^^^^^^
// Type 'Element' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 173 more.
Personally I don't actually like using generics for unsafe stuff like this; I would probably write:
const element = document.querySelector(".first") as HTMLInputElement
it's explicitly unsafe
Generics are supposed to be safe syntax.
!:thats%
When you use a type parameter in the function, it should generally be inferrable from the arguments.
For example, this is a misuse of generics:
function getMeA<T>(): T {
/* magic */
}
because getMeA<string>() and getMeA<number>() compile to the same code at runtime, there's so way to implement this function safely (other than always throwing); this is just a type cast in disguise. Instead of using a generic here, you should return unknown, and cast at the call site if necessary, to be clear it's an unsafe operation:
-function getMeA<T>(): T {
+function getMeA(): unknown {
/* magic */
}
-getMeA<number>()
+getMeA() as number
One exception to this rule is if you're returning a possibly-empty container of T. For example, these are all perfectly safe, even though the generic can't be inferred from the parameters:
function emptyArray<T>(): Array<T> {
return []
}
function useRef<T>(): { current?: T } {
return {}
}