1/6
Review terms commonly used in TypeScript
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
type
A keyword in TypeScript that we can use to define the shape of data
The basic types in TypeScript include:
String
Boolean
Number
Array
Tuple
Enum
Advanced types
type alias
Provide a way of creating new names for existing types. Don’t define new types; instead, provide an alternative name for an existing type.
type MyNumber = number;
type User = {
id: number;
name: string;
email: string;
}
Interface
Defines a contract that an object must adhere to.
interface Client {
name: string;
address: string;
}
Type vs Interface
We can’t use an interface to alias a primitive type. The interface can only be used for an object type. Therefore, we we need to define a primitive type alias, we use type.
Union
Allow us to describe values that can be one of several types and create unions of various primitive, literal, or complex types. Can only defined using type. But a new union type can be created using two interfaces
type Transport = 'Bus' | 'Car' | 'Bike' | 'Walk';
interface CarBattery {
power: number;
}
interface Engine {
type: string;
}
type HybridCar = Engine | CarBattery;
Function Type
Represents a function’s type signature. Using the type alias, we need to specify the parameters and the return type to define a function type. Can also use an interface to represent the function type.
type AddFn = (num1: number, num2: number) => number;
interface IAdd {
(num1: number, num2: number): number;
}
Declaration merging
A feature that is exclusive to interface. We can define an interface multiple times, and the TypeScript compiler will automatically merge these definitions into a single interface definition.
interface Client {
name: string;
}
interface Client {
age: number;
}
const harry: Client = {
name: 'Harry',
age: 41
}
more terms https://blog.logrocket.com/types-vs-interfaces-typescript/