Questions tagged [typescript]

TypeScript is a typed superset of JavaScript that transpiles to plain JavaScript. It adds optional types to JavaScript. This tag is for questions specific to TypeScript. It is not used for general JavaScript questions.

typescript
Filter by
Sorted by
Tagged with
136 votes
10 answers
49k views

How do I return the response from an Observable/http/async call in angular?

I have service which returns an observable which does an http request to my server and gets the data. I want to use this data but I always end up getting undefined. What's the problem? Service: @...
eko's user avatar
  • 40.2k
184 votes
5 answers
55k views

Transform union type to intersection type

Is there a way to transform a union type into an intersection type : type FunctionUnion = (() => void) | ((p: string) => void) type FunctionIntersection = (() => void) & ((p: string) =>...
Titian Cernicova-Dragomir's user avatar
46 votes
4 answers
14k views

How to define Typescript type as a dictionary of strings but with one numeric "id" property

My existing JavaScript code has "records" where the id is numeric and the other attributes are strings. I'm trying to define this type: type T = { id: number; [key: string]: string } ...
Fred's user avatar
  • 571
226 votes
16 answers
193k views

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

I want to dynamically create a template. This should be used to build a ComponentType at runtime and place (even replace) it somewhere inside of the hosting Component. Until RC4 I was using ...
Radim Köhler's user avatar
1328 votes
7 answers
541k views

In TypeScript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

When looking at the source code for a tslint rule, I came across the following statement: if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) { return; } Notice the ! operator after ...
Mike Chamberlain's user avatar
741 votes
15 answers
973k views

How can I select an element in a component template?

Does anybody know how to get hold of an element defined in a component template? Polymer makes it really easy with the $ and $$. I was just wondering how to go about it in Angular. Take the example ...
Aman Gupta's user avatar
  • 8,033
147 votes
9 answers
77k views

Equivalent of $compile in Angular 2

I want to manually compile some HTML containing directives. What is the equivalent of $compile in Angular 2? For example, in Angular 1, I could dynamically compile a fragment of HTML and append it ...
Michael Kang's user avatar
  • 52.4k
34 votes
2 answers
7k views

Difference between Variance, Covariance, Contravariance, Bivariance and Invariance in TypeScript

Could you please explain using small and simple TypeScript examples what is Variance, Covariance, Contravariance, Bivariance and Invariance?
captain-yossarian from Ukraine's user avatar
686 votes
21 answers
754k views

access key and value of object using *ngFor

I am a bit confused about how to get the key and value of an object in angular2 while using *ngFor for iterating over the object. I know in angular 1.x there is a syntax like ng-repeat="(key, value) ...
Pardeep Jain's user avatar
  • 85.5k
207 votes
6 answers
75k views

Why doesn't Object.keys return a keyof type in TypeScript?

Title says it all - why doesn't Object.keys(x) in TypeScript return the type Array<keyof typeof x>? That's what Object.keys does, so it seems like an obvious oversight on the part of the ...
Ryan Cavanaugh's user avatar
549 votes
10 answers
543k views

Use async await with Array.map

Given the following code: var arr = [1,2,3,4,5]; var results: number[] = await arr.map(async (item): Promise<number> => { await callAsynchronousOperation(item); return item +...
Alon's user avatar
  • 11.2k
1252 votes
29 answers
803k views

How do you explicitly set a new property on `window` in TypeScript?

I setup global namespaces for my objects by explicitly setting a property on window. window.MyNamespace = window.MyNamespace || {}; TypeScript underlines MyNamespace and complains that: The ...
joshuapoehls's user avatar
  • 33.9k
644 votes
29 answers
862k views

How do I cast a JSON Object to a TypeScript class?

I read a JSON object from a remote REST server. This JSON object has all the properties of a typescript class (by design). How do I cast that received JSON object to a type var? I don't want to ...
David Thielen's user avatar
125 votes
14 answers
74k views

Typescript: deep keyof of a nested object

So I would like to find a way to have all the keys of a nested object. I have a generic type that take a type in parameter. My goal is to get all the keys of the given type. The following code work ...
CalibanAngel's user avatar
  • 1,431
2539 votes
25 answers
889k views

Interfaces vs Types in TypeScript

What is the difference between these statements (interface vs type) in TypeScript? interface X { a: number b: string } type X = { a: number b: string };
user avatar
426 votes
33 answers
746k views

Can't perform a React state update on an unmounted component

Problem I am writing an application in React and was unable to avoid a super common pitfall, which is calling setState(...) after componentWillUnmount(...). I looked very carefully at my code and ...
Igor Soloydenko's user avatar
61 votes
7 answers
26k views

How to transform union type to tuple type

For example, I have a type: type abc = 'a' | 'b' | 'c'; How to make a tuple type that contains all elements of the union at compile time? type t = ['a','b', 'c'];
Nail Achmedzhanov's user avatar
32 votes
2 answers
13k views

Typescript: infer type of generic after optional first generic

I have a function with two generic types, In and Out: function createTask< In extends Record<string, any> = {}, Out extends Record<string, any>, >(task : TaskFunction<In, Out&...
woubuc's user avatar
  • 881
128 votes
2 answers
27k views

How can I see the full expanded contract of a Typescript type?

If I have a collection of types that looks a bit like this: type ValidValues = string | number | null type ValidTypes = "text" | "time" | "unknown" type Decorated = { ...
suddjian's user avatar
  • 2,226
242 votes
9 answers
219k views

TypeScript: Object.keys return string[]

When using Object.keys(obj), the return value is a string[], whereas I want a (keyof obj)[]. const v = { a: 1, b: 2 } Object.keys(v).reduce((accumulator, current) => { accumulator....
jeanpaul62's user avatar
  • 9,991
771 votes
23 answers
969k views

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

Trying out TypeScript for a React project and I'm stuck on this error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ train_1: boolean; ...
DLee's user avatar
  • 8,656
373 votes
25 answers
576k views

How to apply filters to *ngFor?

Apparently, Angular 2 will use pipes instead of filters as in Angular1 in conjunction with ng-for to filter results, although the implementation still seems to be vague, with no clear documentation. ...
Khaled's user avatar
  • 8,345
258 votes
5 answers
162k views

How to fix TS2322: "could be instantiated with a different subtype of constraint 'object'"?

A have a type-check error in recursive types. I am trying to write types for react-jss styles object. type StylesFn<P extends object> = ( props: P ) => CSS.Properties<JssValue<P>&...
teux's user avatar
  • 2,690
455 votes
10 answers
316k views

What is the difference between Subject and BehaviorSubject?

I'm not clear on the difference between a Subject and a BehaviorSubject. Is it just that a BehaviorSubject has the getValue() function?
Mike Jerred's user avatar
  • 10.1k
17 votes
2 answers
3k views

Type union not checking for excess properties [duplicate]

let's imagine a have an object that either have properties A and B or C, e.g.: const temp = { A: 1, B: 2, } or const temp = { C: 3, } And intuitively I see this type as: type T = {A: number, ...
qwerty qwerty's user avatar
468 votes
12 answers
246k views

Is there a `valueof` similar to `keyof` in TypeScript?

I want to be able to assign an object property to a value given a key and value as inputs yet still be able to determine the type of the value. It's a bit hard to explain so this code should reveal ...
styfle's user avatar
  • 23.4k
1030 votes
39 answers
1.6m views

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

I read how TypeScript module resolution works. I have the following repository: @ts-stack/di. After compiling the directory structure is as follows: ├── dist │   ├── annotations.d.ts │   ├── ...
ktretyak's user avatar
  • 29.5k
36 votes
3 answers
6k views

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

I was surprised to find that TypeScript won't complain at me doing something like this: type sth = { value: number, data: string } | { value: number, note: string }; const a: sth = { value: 7, data: '...
Tomáš Hübelbauer's user avatar
446 votes
23 answers
498k views

Expression ___ has changed after it was checked

Why is the component in this simple plunk @Component({ selector: 'my-app', template: `<div>I'm {{message}} </div>`, }) export class App { message:string = 'loading :('; ...
drew moore's user avatar
77 votes
3 answers
45k views

In TypeScript, how to get the keys of an object type whose values are of a given type?

I've been trying to create a type that consists of the keys of type T whose values are strings. In pseudocode it would be keyof T where T[P] is a string. The only way I can think of doing this is in ...
Aron's user avatar
  • 8,968
348 votes
19 answers
266k views

Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]

I have a problem with HTTP in Angular. I just want to GET a JSON list and show it in the view. Service class import {Injectable} from "angular2/core"; import {Hall} from "./hall"; import {Http} ...
Claudiu Matei's user avatar
30 votes
1 answer
2k views

What does "homomorphic mapped type" mean?

I've seen the term "homomorphic mapped type" in a few TypeScript PRs. Here's an example: https://github.com/microsoft/TypeScript/pull/21919 In --strictNullChecks mode, when a homomorphic mapped ...
Max Heiber's user avatar
  • 14.9k
1336 votes
52 answers
1.4m views

Can't bind to 'formGroup' since it isn't a known property of 'form'

The situation I am trying to make what should be a very simple form in my Angular application, but no matter what, it never works. The Angular version Angular 2.0.0 RC5 The error Can't bind to '...
FrancescoMussi's user avatar
420 votes
21 answers
876k views

How do I pass data to Angular routed components?

In one of my Angular 2 routes's templates (FirstComponent) I have a button first.component.html <div class="button" click="routeWithData()">Pass data and route</div> My goal is to ...
dragonmnl's user avatar
  • 15k
228 votes
23 answers
353k views

How to load external scripts dynamically in Angular?

I have this module which componentize the external library together with additional logic without adding the <script> tag directly into the index.html: import 'http://external.com/path/file.js' ...
CallMeLaNN's user avatar
  • 8,428
935 votes
37 answers
1.3m views

Property '...' has no initializer and is not definitely assigned in the constructor

in my Angular app i have a component: import { MakeService } from './../../services/make.service'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-vehicle-form', ...
Mikhail Kostiuchenko's user avatar
261 votes
11 answers
194k views

typescript interface require one of two properties to exist

I'm trying to create an interface that could have export interface MenuItem { title: string; component?: any; click?: any; icon: string; } Is there a way to require component or click to be ...
Nix's user avatar
  • 57.7k
243 votes
6 answers
82k views

Derive union type from tuple/array values

Say I have an array: const list = ['a', 'b', 'c'] Is it possible to derive from this value union type that is 'a' | 'b' | 'c'? I want this because I want to define type which allows only values from ...
WHITECOLOR's user avatar
  • 25.6k
91 votes
6 answers
83k views

How do I share data between components in Angular 2?

In Angular 1.x.x you simply ask for the same service and you end up with the same instance, making it possible to share the data in the service. Now in Angular 2 I have a component that has a ...
Per Hornshøj-Schierbeck's user avatar
73 votes
8 answers
28k views

Does TypeScript support mutually exclusive types?

I have a method that takes a parameter. I would like TypeScript to verify that the object being passed in (at compile-time, I understand run-time is a different animal) only satisfies one of the ...
Brian Ball's user avatar
  • 12.5k
745 votes
36 answers
1.5m views

Unable to resolve dependency tree error when installing npm packages

When trying to install the npm packages using npm i command, I am getting the following exception: I have tried reinstalling the Node.js package and setting the proxy to off using: set HTTP_PROXY= ...
Pearl's user avatar
  • 8,849
671 votes
30 answers
844k views

Interface type check with Typescript

This question is the direct analogon to Class type check in TypeScript I need to find out at runtime if a variable of type any implements an interface. Here's my code: interface A { member: string;...
lhk's user avatar
  • 28.6k
134 votes
13 answers
133k views

Angular 2 Sibling Component Communication

I have a ListComponent. When an item is clicked in ListComponent, the details of that item should be shown in DetailComponent. Both are on the screen at the same time, so there's no routing involved....
dennis.sheppard's user avatar
2122 votes
51 answers
1.7m views

Can't bind to 'ngModel' since it isn't a known property of 'input'

I have this simple input in my component which uses [(ngModel)] : <input type="text" [(ngModel)]="test" placeholder="foo" /> And I get the following error when I ...
Anthony Brenelière's user avatar
765 votes
11 answers
277k views

'unknown' vs. 'any'

TypeScript 3.0 introduces unknown type, according to their wiki: unknown is now a reserved type name, as it is now a built-in type. Depending on your intended use of unknown, you may want to ...
Jac Mos's user avatar
  • 8,266
338 votes
15 answers
813k views

Angular File Upload

I'm a beginner with Angular, I want to know how to create Angular 5 File upload part, I'm trying to find any tutorial or doc, but I don't see anything anywhere. Any idea for this? And I tried ng4-...
core114's user avatar
  • 5,295
641 votes
24 answers
837k views

TypeScript getting error TS2304: cannot find name ' require'

I am trying to get my first TypeScript and DefinitelyTyped Node.js application up and running, and running into some errors. I am getting the error "TS2304: Cannot find name 'require' " when I ...
JerryKur's user avatar
  • 7,409
95 votes
5 answers
83k views

Generic type to get enum keys as union string in typescript?

Consider the following typescript enum: enum MyEnum { A, B, C }; If I want another type that is the unioned strings of the keys of that enum, I can do the following: type MyEnumKeysAsStrings = ...
Stephan G's user avatar
  • 3,489
293 votes
10 answers
224k views

How do I use namespaces with TypeScript external modules?

I have some code: baseTypes.ts export namespace Living.Things { export class Animal { move() { /* ... */ } } export class Plant { photosynthesize() { /* ... */ } } } dog.ts import ...
Ryan Cavanaugh's user avatar
286 votes
19 answers
524k views

How do I initialize a TypeScript Object with a JSON-Object?

I receive a JSON object from an AJAX call to a REST server. This object has property names that match my TypeScript class (this is a follow-on to this question). What is the best way to initialize it?...
David Thielen's user avatar

1
2 3 4 5
333