Introducing TypeScript Flashcards
Why can’t TypeScript run directly in a browser?
It must be transpiled into JavaScript first.
What is the main benefit of TypeScript over JavaScript?
It adds a rich type system to JavaScript.
What is the purpose of the unknown type in TypeScript?
It is used when the type is uncertain but requires type safety.
What must be done before using a variable of type unknown?
It must be explicitly checked before use.
What is a type predicate in TypeScript?
A function that verifies a value’s type.
How do you define a custom type in TypeScript?
Using the type keyword.
What operator is used to extend types in TypeScript?
The &
(intersection) operator.
How do you define a type alias for a product with an optional price in TypeScript?
type Product = { name: string; unitPrice?: number };
How do you create a DiscountedProduct type that extends Product?
type DiscountedProduct = Product & { discount: number };
What does the following TypeScript snippet do?
fetch("https://swapi.dev/api/people/1") .then((response) => response.json()) .then((data: unknown) => { if (isCharacter(data)) { console.log("name", data.name); } });
It fetches data from an API, ensures type safety by using unknown, and checks the type before accessing properties.