All topics

TypeScript interview questions

19 questions with answers. 1,145 open jobs in India ask for TypeScript.

  1. 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)

  2. 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)

  3. When to use JSX.Element vs ReactNode vs ReactElement?

    What is the difference between JSX.Element, ReactNode, and ReactElement?

    A ReactElement is an object with type, props, and key properties:

    interface ReactElement<
      P = any,
      T extends
        | string
        | JSXElementConstructor<any> = string
        | JSXElementConstructor<any>,
    > {
      type: T;
      props: P;
      key: string | null;
    }
    

    A JSX.Element is a ReactElement<any, any>. It exists as various libraries can implement JSX in their own way:

    declare global {
      // …
      namespace JSX {
        // …
        interface Element extends React.ReactElement<any, any> {}
        // …
      }
      // …
    }
    

    A ReactPortal is a ReactElement with a children property:

    interface ReactPortal extends ReactElement {
      children: ReactNode;
    }
    

    A ReactNode is a ReactElement, string, number, Iterable<ReactNode>, ReactPortal, boolean, null, or undefined:

    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.render returns a ReactNode:

    class Component<P, S> {
      // …
      render(): ReactNode;
      // …
    }
    

    A FunctionComponent returns a ReactElement<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 | null just 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)

  4. 'unknown' vs. 'any'

    You can read more about unknown in 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 variable
    

    The 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)

  5. 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 callback parameter's type must be "function that accepts a number and returns type any":

    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); // OK
    

    If 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)

  6. 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` tag
    

    Workaround: 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)

  7. 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)

  8. Is there a way to check for both `null` and `undefined`?

    Using a juggling-check, you can test both null and undefined in one hit:

    if (x == null) {
    

    If you use a strict-check, it will only be true for values set to null and 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)

  9. What is the Record type?
    1. Can someone give a simple definition of what Record is?

    A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

    1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

    As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

    1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

    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 properties
    

    and sometimes accepted:

    const y = {a: "hey", b: "you"};
    acceptR(y); // okay
    
    1. With 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)

  10. 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 null or undefined. 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.

    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 returns null.

    There are probably lots of other examples, too.

    From Stack Overflow: asked by Marty Pitt, answered by Donut (CC BY-SA 4.0)

  11. The difference between "require(x)" and "import x"

    This simple image will help to you understand the differences between require and import.

    Apart from that,

    You can't selectively load only the pieces you need with require but with import, you can selectively load only the pieces you need, which can save memory.

    Loading is synchronous(step by step) for require on the other hand import can be asynchronous(without waiting for previous import) so it can perform a little better than require.

    From Stack Overflow: asked by austinthemassive, answered by A l w a y s S u n n y (CC BY-SA 4.0)

  12. 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;
    

    String is the JavaScript String type, which you could use to create new strings. Nobody does this as in JavaScript the literals are considered better, so s2 in the example above creates a new string without the use of the new keyword and without explicitly using the String object.

    string is the TypeScript string type, which you can use to type variables, parameters and return values.

    Additional notes...

    Currently (Feb 2013) Both s1 and s2 are valid JavaScript. s3 is 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 type
    

    From Stack Overflow: asked by Paul0515, answered by Fenton (CC BY-SA 3.0)

  13. @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>
    

    ContactCard is 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)

  14. 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 keyof gives you the union of all possible property key types. Let's help those people first. You can make a ValueOf analogous to keyof, by using indexed access types with keyof T as the key, like so:

    type ValueOf<T> = T[keyof T];
    

    which gives you

    type Foo = { a: string, b: number };
    type ValueOfFoo = ValueOf<Foo>; // string | number
    

    ALSO: If you're creating an object literal and need the union of those property values as literal types like "0" instead of string, then you might want to use a const assertion; 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 Foo
    

    In 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 Date
    

    The idea is that the key parameter allows the compiler to infer the generic K parameter. Then it requires that value matches JWT[K], the indexed access type you need.

    From Stack Overflow: asked by styfle, answered by jcalz (CC BY-SA 4.0)

  15. (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 @Output of 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 ngModel events 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 "ngModel things"

    <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)

  16. How to convert a string to number in TypeScript?

    Exactly like in JavaScript, you can use the parseInt or parseFloat functions, 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 (like null).

    Table taken from this answer

    From Stack Overflow: asked by Paul0515, answered by Ryan Cavanaugh (CC BY-SA 4.0)

  17. 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 null or undefined here, so don't complain about the possibility of it being null or undefined." 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 operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms <T>x and x 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)

  18. 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 window interface 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)

  19. 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.