typescript basic knowledge sorting

Posted by jrbush82 on Mon, 14 Feb 2022 13:05:40 +0100

I Foundation type


  1. Throw exception
  2. Function expression with no return value


// The function returning never must have an unreachable end point
function error(message: string): never {
    throw new Error(message);

// The inferred return value type is never
function fail() {
    return error("Something failed");

// The function returning never must have an unreachable end point
function infiniteLoop(): never {
    while (true) {

Usually used to indicate that a function has no return value


function warnUser(): void {
    console.log("This is my warning message");

Common array type definition:

Array generics:

Tuple type:
Represents an array of known element numbers and types


// Declare a tuple type
let x: [string, number];
// Initialize it
x = ['hello', 10]; // OK
// Initialize it incorrectly
x = [10, 'hello']; // Error

Enumeration type:
One convenience provided by enumeration type is that you can get its name from the value of enumeration. For example, we know the value, but we are not sure which name it maps to. We can find the corresponding name


// By default, elements are numbered from 0; You can also manually specify the value of the member 
enum Color {Red, Green, Blue}
let c: Color = Color.Green;

Type assertion: it has no run-time impact, but works at the compilation stage
Type assertion can tell the compiler that I know what the current type is (TypeScript will assume that you have made the necessary checks)
Two expressions:

  1. Angle bracket syntax

    let someValue: any = "this is a string";
    let strLength: number = (<string>someValue).length;
  2. as grammar

    let someValue: any = "this is a string";
    let strLength: number = (someValue as string).length;

Other common foundation types are:
object: non original type
Any: any type
boolean: boolean value
Number: number type
String: string type
Null and Undefined

II Interface
How interfaces work:
The type checker will check the calls of the interface, and the compiler will only check whether those required attributes exist and whether their types match

Read only attribute:
You can only modify the value of an object when it is just created
(an error will be reported if the object value is initialized and then assigned)

interface Point {
    readonly x: number;
    readonly y: number;

TypeScript has readonlyarray < T > type to ensure that the array cannot be modified after it is created
**Read only properties cannot be assigned to other types

let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
a = ro; // error!
// Available type assertions
a = ro as number[];

Function type:

// definition
interface SearchFunc {
  (source: string, subString: string): boolean;

The parameters of the function will be checked one by one, and the parameter types in the corresponding positions are required to be compatible
For type checking of function type, the parameter name of the function does not need to match the name defined in the interface

// use
let mySearch: SearchFunc;
mySearch = function(src: string, sub: string): boolean {
  let result = src.search(sub);
  return result > -1;

Index type:
Not yet

III generic paradigm
Use the type variable t (generic parameter names can use any name) to represent generics

// T helps us capture the user's incoming and return types
function identity<T>(arg: T): T {
    return arg;

It can be used in two ways:

  1. Pass in all parameters, including type parameters

    // Explicitly specify that T is a string type and pass it to the function as a parameter, using < >
    let output = identity<string>("myString");  // type of output will be 'string'
  2. Type inference is used -- that is, the compiler will automatically help us determine the type of T according to the passed parameters

    // Instead of using angle brackets (< >) to explicitly pass in a type, the compiler can look at the value of myString and set T to its type
    let output = identity("myString");  // type of output will be 'string'

    Note: if the compiler does not automatically infer the type, it can only explicitly pass in the type of T

Generic variable:
This generic type variable must be used correctly in the function body

function loggingIdentity<T>(arg: T): T {
    console.log(arg.length);  // Error: T doesn't have .length
    return arg;
// Generic constraints
function loggingIdentity<T>(arg: T[]): T[] {  // T [] can be expressed as array < T >
    console.log(arg.length);  // Array has a .length, so no more error
    return arg;

Define generic interfaces:

interface GenericIdentityFn {
    <T>(arg: T): T;
function identity<T>(arg: T): T {
    return arg;
let myIdentity: GenericIdentityFn = identity;
// Explicit generic type
let myIdentity: GenericIdentityFn<number> = identity;

Generic class:

class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

Generic constraints:
You need to list the constraint requirements for T and define an interface to describe the constraint conditions

interface Lengthwise {
    length: number;

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length);  // Now we know it has a .length property, so no more error
    return arg;

Topics: Front-end TypeScript