50 Difficult TypeScript Interview Questions

These questions will expand your knowledge and grow your understanding of TypeScript. I meticulously studied the TypeScript docs to come up with this list. Let me know in the comments if you enjoyed it!

If you enjoy this list of questions, check out my list of 50 difficult JavaScript interview questions.

1. What does the typing on countWheels below require?

interface Vehicle {
countWheels(this: Vehicle): () => number;
}

Answer:

It requires countWheels to be called by an object of type Vehicle.

2. True or False? The below is valid.

interface Window {
name: string;
}interface Window {
app: string;
}

Answer:

True. Window now has both name and app.

3. How do you limit the values a string can be assigned to?

Answer:

Simply define exact string values that the object or variable can have assigned to it. For example:

let stringOptions: ‘optOne’ | ‘optTwo’;

4. What does the void keyword do for functions when assigned as their return value? What does void do when used as a variable type?

Answer:

When used as a return type it means there is no return. When used as a variable type, the code compiles but it’s not useful.

5. What is an advantage of using generics over ‘any’?

Answer:

Generics retain information. For example, if a string is passed as the generic param and the function returns the generic param, then any calling function knows it will receive a string as the return value type.

Another reason is that a function can require that the passed generic be an extension of an interface. This lets you guarantee that the passed generic must have certain functions on it.

6. What is the name of the TypeScript feature that allows a value to be (for example) either a number or a string?

Answer:

Union types.

7. True or False? The following code compiles.

interface Dog{
hair: boolean;
bloodType: 'warm';
}interface Snake{
scales: boolean;
bloodType: 'cold';
}const myCreature = (creature: Dog | Snake) => {
console.log(creature.scales);
}

Answer:

False. When using union types, only members common to both fields are accessible.

8. How do you create an array with all mutating methods removed?

Answer:

Use the ReadonlyArray type.

let readOnly: ReadonlyArray<string> = ['a','b','c'];
readOnly.push('d');

9. Show the syntax for converting ‘object’ from its existing type to a string.

Answer:

object as unknown as string

An example of when this is useful is when you get data from an endpoint or poorly typed library.

10. What is the name of the technique where you use a single field of literal types to let TypeScript narrow down the possible current type?

Answer:

Discriminating Unions

11. What is the inferred return type of the below function:

function iFailed() {
return error("I failed");
}

Answer:

The never type.

12. If — strictNullChecks is off, why can null and undefined be assigned to a let variable of type string or number?

Answer:

null and undefined are subtypes of all other types.

13. True or False? Rest params do not need to be explicitly mentioned or typed in TypeScript?

Answer:

False. Rest params should be typed, for example: …rest: string[].

14. True or False? The two following functions are identically typed?

function cityState(city: string, state = "Smith") {...}
function cityState(city: string, state? = "Smith") {...}

Answer:

True. Default parameters are optional.

15. Evaluate the code below. True or False? The value of ‘name’ in ‘person’ can be any string value.

interface A {
name: string;
age: number;
}
interface B {
name: 'Jon' | 'Jim';
address: string;
}
// const person : B & A

Answer:

False. It must be Jon or Jim. The order of the intersection of types does not matter.

16. Create an interface name APIData that has an unknown number of keys and constrains the values to types ‘string’ or ‘number’.

Answer:

interface APIData {
[key: string]: string | number
}

17. How can you ensure that a function that accepts a generic parameter will work with types that have the .add property?

Answer:

interface Adder {
add: number;
}function counter<T extends Adder>(arg: T): T {...}

18. What are two reasons a developer might use an enum?

Two Possible Answers:

To document intent or create a set of distinct cases.

19. Why might you constrain a property type to true?

Answer:

You might use it to constrain object values whose property types are interrelated, i.e.

interface CallSuccess {
success: true;
error: null;
};interface CallFailure {
success: false;
error: string;
};

20. What is the difference in the type below?

const myConst = "Hello";
let myLet = "Hello";

Answer:

myConst is of type “Hello”, myLet is of type string. This is because the value of myLet can change, so the type needs to be looser.

21. What is a tuple?

Answer:

A tuple is an array with a fixed number of elements whose types are known and may or may not be the same.

22. How can types be extended?

Answer:

They can’t directly but can be through intersection, i.e.:

type MotorVehicle = {
wheels: number;
}
type Car = MotorVehicle & {
make: string;
}const car: Car = {
wheels: 4,
make: 'Toyota'
}

23. What is a one-line type guard for null types?

A possible answer:

function myFunc(str: string | null): string {
return str || 'str was null';
}

24. What is the default value of an optional param?

Answer:

The default value is undefined.

25. Give an example of how to check the type of an object.

A possible answer:

interface Motorcycle {
wheels: string;
}interface Car {
windshieldWiperBrand: string;
}function isCar(vehicle: Car | Motorcycle): vehicle is Car{
return (vehicle as Car).windshieldWiperBrand !== undefined;
}

Enjoying these questions so far? Click here for 50 Difficult JavaScript Interview Questions.

26. What is Union Exhaustiveness Checking?

Answer:

Union Exhaustiveness Checking is covering all the variants of a discriminated union. For example, a switch statement that checks for all the finite possible values of a property on an object has exhaustively checked the union.

27. What is the difference between string[] and [string]?

Answer:

string[] is an array, it can only contain strings, and is of indeterminate length.

[string] is a tuple. In this case, it can only contain only one string, but (for example)[string, number] would allow it to contain a string and a number. The type and length are both fixed.

28. What is type assertion and what does the syntax look like?

Answer:

Type assertion is when you inform the compiler that an object or variable is of a certain type. The syntax can be either of the below.

let char0: string = (someValue as string).charAt(0);
let char0: string = (<string>someValue).charAt(0);

29. What is the only type assertion syntax compatible with JSX?

Answer:

JSX requires the as type assertion syntax.

30. What does assertNever do?

Answer:

It does a check on an object and returns true if the type is never.

31. Will the following code compile?

declare const iDontKnow: unknown;if (typeof iDontKnow === string) {
const aString: string = iDontKnow;
}

Answer:

It will not compile. typeof returns a string value, in the case of the code above typeof iDontKnow returns the value ‘string’. Otherwise, the code above is fine. An unknown could be of type string, and the if check allows iDontKnow to be assigned to a string const.

32. How might you type an array of objects that have an unknown amount of keys and values of type number?

Answer:

obj: { [key: string]: number }[];

33. Does TypeScript recommend using Number, String, and Boolean (the objects) or number, string, and boolean (the primitives)?

Answer:

TypeScript recommends that the primitives primarily be used. See here for the docs recommendations.

34. True or False? TypeScript can infer type (called contextual typing) for functions as well as for primitive variables?

Answer:

The answer is True. You can choose to explicitly type out the function, but the compiler will readily infer the type from the assigned value of the function. Read here for more details.

35. Why should a developer avoid using the ‘any’ type?

Answer:

While there could be a number of answers to this, ‘any’ should primarily be avoided because you lose type safety.

More situational answers may include: you lose information about the types you are working with, other developers lose metadata about your code, TypeScript puts rules in place to avoid bugs and you shouldn’t shortcut those rules, etc.

36. True or False? It is valid to have two back-to-back types declared for the same function, like in the following example.

function summingFunction(x: number, y: number): number;function summingFunction(x: number, y: number, z: string): {value: number; name: string};

Answer:

The answer is True. This is called overloading. Overloading is a common pattern in JavaScript; sometimes a developer will pass a different set of params to the same function and expect different return value.

37. How do you create a class that receives a generic type parameter?

Answer:

class MyClass<T> {...}

38. Give an example of a function where one type parameter is constrained by another type parameter.

A possible answer:

function getString<T, S extends keyof T>(obj: T, key: S) {
return obj[key];
}let strObject = { a: 'my', b: 'string', c: 'object' };getString(strObject, 'a');
getString(strObject, 'z');

39. Show an example of a generic type constrained by an interface.

A possible answer:

interface Currency {
name: string;
value: number;
}interface Coins extends Currency {
material: string
}function printValue<T extends Currency>(currency: T): void {
console.log(currency.value);
}let dime: Coins = {
name: 'Dime',
value: 0.10,
material: 'metal'
}printValue(dime);

40. In the example from #39, will the code compile if you call printValue with a parameter of type Currency but not of type Coins?

Answer:

It will. T extends Currency, and that means T can be of type Currency as well as anything that extends Currency. See below:

41. True or False? In the example from #39, the code will compile if printValue is called with the below object (dollar).

interface Paper {
name: string;
value: number;
personPictured: string;
}let dollar: Paper = {
name: 'Dollar Bill',
value: 1,
personPictured: 'George Washington'
}

Answer:

True. Even though Paper doesn’t explicitly extend Currency, it satisfies the type properties of Currency. Therefore dollar can be passed as though it is an object of type Currency.

42. Does TypeScript support numeric literal types?

Answer:

Yes. Below is an example use case.

interface Student {
grade: 1 | 2 | 3 | 4;
name: string;
}

43. What does the ‘protected’ modifier on a class property do?

Answer:

It limits access of that member only to classes that are derived from (extend) the parent class.

44. True or False? Abstract classes cannot contain concrete methods.

Answer:

False. Abstract classes cannot be instantiated directly, but they can contain concrete methods (methods with implementation details) which any deriving classes will inherit.

45. What is the value of Compass.South in the code below?

enum Compass {
North,
East,
South,
West
}

Answer:

Compass.South equals 2. Enums start at 0 by default and auto increment by 1.

46. What is the method signature of console.log when TypeScript is enabled?

Answer:

Console.log(...data: any[]): void

Native JavaScript functions are typed in TypeScript.

47. True or False? The following does not compile.

enum Compass {
North = 0,
East = '1',
South = 2,
West = '3'
}

Answer:

The answer is False, it does compile. Enums can be a mix of string and number values.

48. True or False? super() must be called before a property is accessed on this in a constructor body if the class extends another class.

Answer:

True.

49. Assume Car extends MotorVehicle. True or False? The following code compiles.

let prius: MotorVehicle = new Car();

Answer:

True. Since MotorVehicle is the parent class of Car, prius can be initialized as a Car and it is still true that it is of type MotorVehicle.

50. True or False? The ‘protected’ modifier cannot be used on the constructor of a base class?

Answer:

False. The ‘protected’ modifier can be used on constructors and prevents other non-child classes from creating an instance of the class.


Are you a developer looking to start your first side business? Learn how here.

Share this post:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.