How can I declare a global variable in Angular 2 and up / Typescript? [closed]

Here is the simplest solution without Service or Observer: Put the global variables in a file and export them. // // ===== File globals.ts // ‘use strict’; export const sep=”https://stackoverflow.com/”; export const version: string=”22.2.2″; To use globals in another file, use an import statement: import * as myGlobals from ‘globals’; Example: // // ===== File … Read more

TypeScript: Why can’t I assign a valid field of an object with type { a: “a”, b: “b” }

I believe this is because objects are contravariant in their key types. For more information see this answer. Likewise, multiple candidates for the same type variable in contra-variant positions causes an intersection type to be inferred. const paths = [‘a’, ‘b’] as const type Path = typeof paths[number] type PathMap = { [path in Path]: … Read more

Typescript: accessing an array element does not account for the possibility of undefined return values

UPDATE for TS 4.1: TypeScript 4.1 introduced a –noUncheckedIndexedAccess compiler flag that implements the suggestion in microsoft/TypeScript#13778 to account for undefined in this way. Note that the feature will not be enabled as part of the –strict set of compiler options and is being called “pedantic index signatures” because it will end up complaining about … Read more

How to use select/option/NgFor on an array of objects in Angular2 [duplicate]

I don’t know what things were like in the alpha, but I’m using beta 12 right now and this works fine. If you have an array of objects, create a select like this: <select [(ngModel)]=”simpleValue”> // value is a string or number <option *ngFor=”let obj of objArray” [value]=”obj.value”>{{obj.name}}</option> </select> If you want to match on … Read more

TypeScript: Define a union type from an array of strings

TypeScript 3.4 added const assertions which allow for writing this as: const fruits = [“Apple”, “Orange”, “Pear”] as const; type Fruits = typeof fruits[number]; // “Apple” | “Orange” | “Pear” With as const TypeScript infers the type of fruits above as readonly[“Apple”, “Orange”, “Pear”]. Previously, it would infer it as string[], preventing typeof fruits[number] from … Read more