Function parameter and return type definitions

This is my second day of the more text Challenge. For details, see more text Challenge

Type annotations and type inference

  1. If TS could automatically analyze variable types, we wouldn’t need to do anything
  2. If TS cannot analyze variable types, we need to use type annotations
// Note through the form:
function getTotal(one: number, two: number) {
    return one + two;
}
  
 const total = getTotal(1.2);

// Deduce the form placed by the mouse
let countInference = 123;
Copy the code

1. Normal function parameter comments return the definition

function getTotal(one: number, two: number) :number {
    return one + two;
  }
  
  const total = getTotal(1.2);
Copy the code

2. Define a method when the function returns no value

function sayHello() :void {
    console.log("hello world");
}
Copy the code

3. Never Return value type

If a function will never finish, you can define a value of never, such as when the execution throws an exception, it will never finish, or if it is an infinite loop

function errorFuntion() :never {
  throw new Error(a);console.log("Hello World");
}
Copy the code

4. If the function arguments are objects (destruct), do not write as above


function add({ one, two }: { one: number, two: number }) :number {
  return one + two;
}

const three = add({ one: 1.two: 2 });

function getNumber({ one }: { one: number }) :number {
  return one;
}

const one = getNumber({ one: 1 });
Copy the code