TypeScript interview questions
19 questions with answers. 1,145 open jobs in India ask for TypeScript.
Interfaces vs Types in TypeScript
Update March 2021: The newer TypeScript Handbook (also mentioned in nju-clc answer below) has a section Interfaces vs. Type Aliases which explains the differences.
Original Answer (2016)
As per the (now archived) TypeScript Language Specification:
Unlike an interface declaration, which always introduces a named object type, a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.
The specification goes on to mention:
Interface types have many similarities to type aliases for object type literals, but since interface types offer more capabilities they are generally preferred to type aliases. For example, the interface type
interface Point { x: number; y: number; }could be written as the type alias
type Point = { x: number; y: number; };However, doing so means the following capabilities are lost:
- An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot No longer true since TS 2.7.
- An interface can have multiple merged declarations, but a type alias for an object type literal cannot.
From Stack Overflow: asked by user6101582, answered by Binary Birch Tree (CC BY-SA 4.0)
What is TypeScript and why should I use it instead of JavaScript?
I originally wrote this answer when TypeScript was still hot-off-the-presses. Five years later, this is an OK overview, but look at Lodewijk's answer below for more depth
1000ft view...
TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.
To get an idea of what I mean, watch Microsoft's introductory video on the language.
For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.
It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza). These days, other IDEs offer TypeScript support too.
Are there other technologies like it?
There's CoffeeScript, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for tools through its optional static typing (see this recent blog post for a little more critique). There's also Dart but that's a full on replacement for JavaScript (though it can produce JavaScript code)
Example
As an example, here's some TypeScript (you can play with this in the TypeScript Playground)
class Greeter { greeting: string; constructor (message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } }And here's the JavaScript it would produce
var Greeter = (function () { function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; return Greeter; })();Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.
It's also capable of inferring types which aren't explicitly declared, for example, it would determine the
greet()method returns a string.Debugging TypeScript
Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio
Want to know more?
I originally wrote this answer when TypeScript was still hot-off-the-presses. Check out Lodewijk's answer to this question for some more current detail.
From Stack Overflow: asked by Mohammed Thabet, answered by Paul Dixon (CC BY-SA 4.0)
When to use JSX.Element vs ReactNode vs ReactElement?
What is the difference between
JSX.Element,ReactNode, andReactElement?A
ReactElementis an object withtype,props, andkeyproperties:interface ReactElement< P = any, T extends | string | JSXElementConstructor<any> = string | JSXElementConstructor<any>, > { type: T; props: P; key: string | null; }A
JSX.Elementis aReactElement<any, any>. It exists as various libraries can implementJSXin their own way:declare global { // … namespace JSX { // … interface Element extends React.ReactElement<any, any> {} // … } // … }A
ReactPortalis aReactElementwith achildrenproperty:interface ReactPortal extends ReactElement { children: ReactNode; }A
ReactNodeis aReactElement,string,number,Iterable<ReactNode>,ReactPortal,boolean,null, orundefined:type ReactNode = | ReactElement | string | number | Iterable<ReactNode> | ReactPortal | boolean | null | undefined;Example:
<div> // <- ReactElement <Component> // <- ReactElement {condition && 'text'} // <- ReactNode </Component> </div>Why do the render methods of class components return ReactNode, but function components return ReactElement?
This is due to historical reasons.
A
Component.renderreturns aReactNode:class Component<P, S> { // … render(): ReactNode; // … }A
FunctionComponentreturns aReactElement<any, any> | null:interface FunctionComponent<P = {}> { (props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null; propTypes?: WeakValidationMap<P> | undefined; contextTypes?: ValidationMap<any> | undefined; defaultProps?: Partial<P> | undefined; displayName?: string | undefined; }How do I solve this with respect to null?
Type it as
ReactElement | nulljust as React does. Or let TypeScript infer the type.From Stack Overflow: asked by Golo Roden, answered by Jonas Wilms (CC BY-SA 4.0)
'unknown' vs. 'any'
You can read more about
unknownin the PR or the RC announcement, but the gist of it is:[..] unknown which is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.
A few examples:
let vAny: any = 10; // We can assign anything to any let vUnknown: unknown = 10; // We can assign anything to unknown just like any let s1: string = vAny; // Any is assignable to anything let s2: string = vUnknown; // Invalid; we can't assign vUnknown to any other type (without an explicit assertion) vAny.method(); // Ok; anything goes with any vUnknown.method(); // Not ok; we don't know anything about this variableThe suggested usage is:
There are often times where we want to describe the least-capable type in TypeScript. This is useful for APIs that want to signal “this can be any value, so you must perform some type of checking before you use it”. This forces users to safely introspect returned values.
From Stack Overflow: asked by Jac Mos, answered by Titian Cernicova-Dragomir (CC BY-SA 4.0)
Are strongly-typed functions as parameters possible in TypeScript?
Sure. A function's type consists of the types of its argument and its return type. Here we specify that the
callbackparameter's type must be "function that accepts a number and returns typeany":class Foo { save(callback: (n: number) => any) : void { callback(42); } } var foo = new Foo(); var strCallback = (result: string) : void => { alert(result); } var numCallback = (result: number) : void => { alert(result.toString()); } foo.save(strCallback); // not OK foo.save(numCallback); // OKIf you want, you can define a type alias to encapsulate this:
type NumberCallback = (n: number) => any; class Foo { // Equivalent save(callback: NumberCallback) : void { callback(42); } }From Stack Overflow: asked by vcsjones, answered by Ryan Cavanaugh (CC BY-SA 4.0)
What is the syntax for Typescript arrow functions with generics?
Edit
Per @Thomas comment, in newer TS compilers, we can simply do:
const foo = <T,>(x: T) => x;Original Answer
The full example explaining the syntax referenced by Robin... brought it home for me:
Generic functions
Something like the following works fine:
function foo<T>(x: T): T { return x; }However using an arrow generic function will not:
const foo = <T>(x: T) => x; // ERROR : unclosed `T` tagWorkaround: Use extends on the generic parameter to hint the compiler that it's a generic, e.g.:
const foo = <T extends unknown>(x: T) => x;From Stack Overflow: asked by Andreas Frische, answered by jbmilgrom (CC BY-SA 4.0)
What is the type of the 'children' prop?
Just
children: React.ReactNode.From Stack Overflow: asked by Asool, answered by Ridd (CC BY-SA 4.0)
Is there a way to check for both `null` and `undefined`?
Using a juggling-check, you can test both
nullandundefinedin one hit:if (x == null) {If you use a strict-check, it will only be true for values set to
nulland won't evaluate as true for undefined variables:if (x === null) {You can try this with various values using this example:
var a: number; var b: number = null; function check(x, name) { if (x == null) { console.log(name + ' == null'); } if (x === null) { console.log(name + ' === null'); } if (typeof x === 'undefined') { console.log(name + ' is undefined'); } } check(a, 'a'); check(b, 'b');Output
"a == null"
"a is undefined"
"b == null"
"b === null"
From Stack Overflow: asked by David Liu, answered by Fenton (CC BY-SA 4.0)
What is the Record type?
- Can someone give a simple definition of what
Recordis?
A
Record<K, T>is an object type whose property keys areKand whose property values areT. That is,keyof Record<K, T>is equivalent toK, andRecord<K, T>[K]is (basically) equivalent toT.- Is
Record<K,T>merely a way of saying "all properties on this object will have typeT"? Probably not all objects, sinceKhas some purpose...
As you note,
Khas a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something likeRecord<string, T>, but the idiomatic way of doing that is to use an index signature like{ [k: string]: T }.- Does the
Kgeneric forbid additional keys on the object that are notK, or does it allow them and just indicate that their properties are not transformed toT?
It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:
declare const x: Record<"a", string>; x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'and it would treat them as excess properties which are sometimes rejected:
declare function acceptR(x: Record<"a", string>): void; acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known propertiesand sometimes accepted:
const y = {a: "hey", b: "you"}; acceptR(y); // okayWith the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
Yes!
From Stack Overflow: asked by Matthias, answered by jcalz (CC BY-SA 4.0)
- Can someone give a simple definition of what
Does Typescript support the ?. operator? (And, what's it called?)
Yes. As of TypeScript 3.7 (released on November 5, 2019), this feature is supported and is called Optional Chaining:
At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a
nullorundefined. The star of the show in optional chaining is the new?.operator for optional property accesses.Refer to the TypeScript 3.7 release notes for more details.
Prior to version 3.7, this was not supported in TypeScript, although it was requested as early as Issue #16 on the TypeScript repo (dating back to 2014).
As far as what to call this operator, there doesn't appear to be a consensus. In addition to "optional chaining" (which is also what it's called in JavaScript and Swift), there are a couple of other examples:
- CoffeeScript refers to it as the existential operator (specifically, the "accessor variant" of the existential operator):
The accessor variant of the existential operator
?.can be used to soak up null references in a chain of properties. Use it instead of the dot accessor.in cases where the base value may be null or undefined.- C# calls this a null-conditional operator.
a null-conditional operator applies a member access,
?., or element access,?[], operation to its operand only if that operand evaluates to non-null; otherwise, it returnsnull.- Kotlin refers to it as the safe call operator.
There are probably lots of other examples, too.
From Stack Overflow: asked by Marty Pitt, answered by Donut (CC BY-SA 4.0)
The difference between "require(x)" and "import x"
This simple image will help to you understand the differences between
requireandimport.Apart from that,
You can't selectively load only the pieces you need with
requirebut withimport, you can selectively load only the pieces you need, which can save memory.Loading is synchronous(step by step) for
requireon the other handimportcan be asynchronous(without waiting for previous import) so it can perform a little better thanrequire.From Stack Overflow: asked by austinthemassive, answered by A l w a y s S u n n y (CC BY-SA 4.0)
What is the difference between types String and string?
Here is an example that shows the differences, which will help with the explanation.
var s1 = new String("Avoid newing things where possible"); var s2 = "A string, in TypeScript of type 'string'"; var s3: string;Stringis the JavaScript String type, which you could use to create new strings. Nobody does this as in JavaScript the literals are considered better, sos2in the example above creates a new string without the use of thenewkeyword and without explicitly using theStringobject.stringis the TypeScript string type, which you can use to type variables, parameters and return values.Additional notes...
Currently (Feb 2013) Both
s1ands2are valid JavaScript.s3is valid TypeScript.Use of
String. You probably never need to use it, string literals are universally accepted as being the correct way to initialise a string. In JavaScript, it is also considered better to use object literals and array literals too:var arr = []; // not var arr = new Array(); var obj = {}; // not var obj = new Object();If you really had a penchant for the string, you could use it in TypeScript in one of two ways...
var str: String = new String("Hello world"); // Uses the JavaScript String object var str: string = String("Hello World"); // Uses the TypeScript string typeFrom Stack Overflow: asked by Paul0515, answered by Fenton (CC BY-SA 3.0)
@Directive vs @Component in Angular
A @Component requires a view whereas a @Directive does not.
Directives
I liken a @Directive to an Angular 1.0 directive with the option
restrict: 'A'(Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.import {Directive} from '@angular/core'; @Directive({ selector: "[logOnClick]", hostListeners: { 'click': 'onClick()', }, }) class LogOnClick { constructor() {} onClick() { console.log('Element clicked!'); } }Which would be used like so:
<button logOnClick>I log when clicked!</button>Components
A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:
import {Component, View} from '@angular/core'; @Component({ selector: 'contact-card', template: ` <div> <h1>{{name}}</h1> <p>{{city}}</p> </div> ` }) class ContactCard { @Input() name: string @Input() city: string constructor() {} }Which would be used like so:
<contact-card [name]="'foo'" [city]="'bar'"></contact-card>ContactCardis a reusable UI component that we could use anywhere in our application, even within other components. These basically make up the UI building blocks of our applications.In summary
Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.
Sources:
From Stack Overflow: asked by Prasanjit Dey, answered by jaker (CC BY-SA 3.0)
Is there a `valueof` similar to `keyof` in TypeScript?
UPDATE: Looks like the question title attracts people looking for a union of all possible property value types, analogous to the way
keyofgives you the union of all possible property key types. Let's help those people first. You can make aValueOfanalogous tokeyof, by using indexed access types withkeyof Tas the key, like so:type ValueOf<T> = T[keyof T];which gives you
type Foo = { a: string, b: number }; type ValueOfFoo = ValueOf<Foo>; // string | numberALSO: If you're creating an object literal and need the union of those property values as literal types like
"0"instead ofstring, then you might want to use aconstassertion; see @Dima's answer.For the question as stated, you can use individual keys, narrower than
keyof T, to extract just the value type you care about:type sameAsString = Foo['a']; // look up a in Foo type sameAsNumber = Foo['b']; // look up b in FooIn order to make sure that the key/value pair "match up" properly in a function, you should use generics as well as indexed access types, like this:
declare function onChange<K extends keyof JWT>(key: K, value: JWT[K]): void; onChange('id', 'def456'); // okay onChange('expire', new Date(2018, 3, 14)); // okay onChange('expire', 1337); // error. 1337 not assignable to DateThe idea is that the
keyparameter allows the compiler to infer the genericKparameter. Then it requires thatvaluematchesJWT[K], the indexed access type you need.From Stack Overflow: asked by styfle, answered by jcalz (CC BY-SA 4.0)
(change) vs (ngModelChange) in angular
(change)event bound to classical input change event.https://developer.mozilla.org/en-US/docs/Web/Events/change
You can use (change) event even if you don't have a model at your input as
<input (change)="somethingChanged()">(ngModelChange)is the@Outputof ngModel directive. It fires when the model changes. You cannot use this event without ngModel directive.https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L124
As you discover more in the source code,
(ngModelChange)emits the new value.https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L169
So it means you have ability of such usage:
<input (ngModelChange)="modelChanged($event)">modelChanged(newObj) { // do something with new value }Basically, it seems like there is no big difference between two, but
ngModelevents gains the power when you use[ngValue].<select [(ngModel)]="data" (ngModelChange)="dataChanged($event)" name="data"> <option *ngFor="let currentData of allData" [ngValue]="currentData"> {{data.name}} </option> </select>dataChanged(newObj) { // here comes the object as parameter }assume you try the same thing without "
ngModelthings"<select (change)="changed($event)"> <option *ngFor="let currentData of allData" [value]="currentData.id"> {{data.name}} </option> </select>changed(e){ // event comes as parameter, you'll have to find selectedData manually // by using e.target.data }From Stack Overflow: asked by Ramesh Rajendran, answered by omeralper (CC BY-SA 4.0)
How to convert a string to number in TypeScript?
Exactly like in JavaScript, you can use the
parseIntorparseFloatfunctions, or simply use the unary+operator:var x = "32"; var y: number = +x;All of the mentioned techniques will have correct typing and will correctly parse simple decimal integer strings like
"123", but will behave differently for various other, possibly expected, cases (like"123.45") and corner cases (likenull).Table taken from this answer
From Stack Overflow: asked by Paul0515, answered by Ryan Cavanaugh (CC BY-SA 4.0)
In TypeScript, what is the ! (exclamation mark / bang) operator when dereferencing a member?
That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be
nullorundefinedhere, so don't complain about the possibility of it beingnullorundefined." Sometimes the type checker is unable to make that determination itself.It is explained in the TypeScript release notes:
A new
!post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operationx!produces a value of the type ofxwithnullandundefinedexcluded. Similar to type assertions of the forms<T>xandx as T, the!non-null assertion operator is simply removed in the emitted JavaScript code.I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.
From Stack Overflow: asked by Mike Chamberlain, answered by Louis (CC BY-SA 4.0)
How do you explicitly set a new property on `window` in TypeScript?
I just found the answer to this in another Stack Overflow question's answer.
declare global { // Note the capital "W" interface Window { MyNamespace: any; } } window.MyNamespace = window.MyNamespace || {};Basically, you need to extend the existing
windowinterface to tell it about your new property.If you are getting an error where the window property is still not picking up from a .d.ts file, you may need to add
export {}to the file.From Stack Overflow: asked by joshuapoehls, answered by joshuapoehls (CC BY-SA 4.0)
Property '...' has no initializer and is not definitely assigned in the constructor
Just go to tsconfig.json and set
"compilerOptions": { "strictPropertyInitialization": false, ... }to get rid of the compilation error.
Otherwise you need to initialize all your variables which is a little bit annoying
From Stack Overflow: asked by Mikhail Kostiuchenko, answered by Martin Čuka (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA19 questions