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

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

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];