How to assert a type of an HTMLElement in TypeScript?

TypeScript uses ‘<>’ to surround casts, so the above becomes: var script = <HTMLScriptElement>document.getElementsByName(“script”)[0]; However, unfortunately you cannot do: var script = (<HTMLScriptElement[]>document.getElementsByName(id))[0]; You get the error Cannot convert ‘NodeList’ to ‘HTMLScriptElement[]’ But you can do : (<HTMLScriptElement[]><any>document.getElementsByName(id))[0];

Is there a way to define type for array with unique items in typescript?

The only possible way this could work at compile time is if your arrays are tuples composed of literals. For example, here are some arrays with the same runtime values, but with different types in TypeScript: const tupleOfLiterals: [1, 2, 2] = [1, 2, 2]; const tupleOfNonLiterals: [number, number, number] = [1, 2, 2]; const … Read more

Types for function that applys name of function and arguments

The compiler will not be able to understand that this is type safe because it generally does not reason very well about assignability for types that depend on as-yet-unspecified generic type parameters. There is an existing GitHub issue, microsoft/TypeScript#24085, that describes this situation. In fact, it is possible (but not very likely) that in your … Read more

Why does A | B allow a combination of both, and how can I prevent it?

The discussion in issue Microsoft/TypeScript#14094 is relevant here. Types in TypeScript are open in the sense that an object has to have at least the properties described by a type for it to match. So the object { value: 7, data: ‘test’, note: ‘hello’ } matches the type { value: number, data: string }, even … Read more

tech