number | string | boolean

TIP

The key difference is: JavaScript uses "dynamic types" (resolved at runtime),TypeScript uses "static types" (set during development)

202111300509398

function add(a: number, b: number, printResult: boolean, resultPhrase: string) {
  const result = a + b;
  if (showResult) {
    console.log(resultPhrase + result);
  }
  return result;
}
// typescript会自动进行类型推断
const a = 5;
const b = 2.8;
const resultPhrase = "Result is ";
const showResult = true;
add(a, b, showResult, resultPhrase);
 












object

202111300638967

const person = {
  name: "Aeroxian",
  developer: "TypeScript",
};
const person: {
  name: string;
  developer: string;
} = {
  name: "Aeroxian",
  developer: "TypeScript",
};

Array

202111300709280

const hobbies = ["Sports", "Reading"];
for (const hobby of hobbies) {
  console.log(hobby.toUpperCase());
}
const hobbies: string[] = ["Sports", "Reading"];

interface TodoItem{
    id:string,
    title: string,
    completed: boolean
}

let todoItems:TodoItem[] = []  // 声明类型数组

// 在vue中使用的时候
data() {
    return {
        todoItems: [] as TodoItem[]
    }
}

添加一个元素到数组中Push an object to an Array in TypeScript | bobbyhadzopen in new window

Tuple

202111300714524

// tuple
const role: [number, string] = [1, "author"];
// 这不是tuple,它时union类型的数组
// const role2: (string | number)[]
const role2 = [2, "Book2"];

Enum

202111300726655

enum Role {
  ADMIN,	// 默认为0
  READ_ONLY,
  AUTHOR,
}
enum Role {
  ADMIN = 5,
  READ_ONLY,	// 默认递增为6
  AUTHOR,
}
enum Role {
  ADMIN = "ADMIN",
  READ_ONLY = 100,
  AUTHOR = "AUTHOR",
}

// 转为JavaScript就是
var Role;
(function (Role) {
    Role["ADMIN"] = "ADMIN";
    Role[Role["READ_ONLY"] = 100] = "READ_ONLY";
    Role["AUTHOR"] = "AUTHOR";
})(Role || (Role = {}));

Union Type

TIP

combining the basic type

function combine(input1: number | string, input2: number | string) {
  let result;
  if (typeof input1 === "number" && typeof input2 === "number") {
    result = input1 + input2;
  } else {
    result = input1.toString() + input2.toString();
  }
  return result;
}
const combineMoney = combine(100,300.3)
console.log(combineMoney);

const combineMsg = combine('Aeroxian',' learning TypeScript');
console.log(combineMsg);
 













Literal Types⭐

TypeScript: Documentation - literal-typesopen in new window

Literal type结合Union type指明resultConversion参数只能传入’as-number‘ 或者 ’as-text‘ 语义化更加清晰,当调用这个方法的时候就能明确该传入值

function combine(
  input1: number | string,
  input2: number | string,
  resultConversion: "as-number" | "as-text"
) {
  let result;
  if (
    (typeof input1 === "number" && typeof input2 === "number") ||
    resultConversion === "as-number"
  ) {
    result = +input1 + +input2;
  } else {
    result = input1.toString() + input2.toString();
  }
  return result;
}

const combineMoney1 = combine(100, 300.3, "as-number");
console.log(combineMoney1); //  400.3
const combineMoney2 = combine("100", "300.3", "as-number");
console.log(combineMoney2); //  400.3



 

















Type Aliases⭐

type Combineable = number | string;
type ConversionDescriptor = "as-number" | "as-text";

function combine(
  input1: Combineable,
  input2: Combineable,
  resultConversion: ConversionDescriptor
) {
  let result;
  if (
    (typeof input1 === "number" && typeof input2 === "number") ||
    resultConversion === "as-number"
  ) {
    result = +input1 + +input2;
  } else {
    result = input1.toString() + input2.toString();
  }
  return result;
}
 
 


 
 
 












void

function printResult(n: number) {
  console.log("Result is" + n);
}

// 等同于
function printResult(n: number): void {
  console.log("Result is" + n);
}

// void等同于
function printResult(n: number): undefined {
  console.log("Result is" + n);
  return;
}





 








Function Type⭐

TIP

Function type allow us to describe which type of function specifically we want to use somewhere

参数类型和返回类型来构成签名

如在回调函数中使用

function addAndHandle(n1: number, n2: number, cb: (result: number) => void) {
  const result = n1 + n2;
  cb(result);
}

addAndHandle(3, 5, (r) => {
  console.log("Result is " + r);
});

 








Function Type的写法有两种,下面这种对象的形式也是可以的

function addAndHandle(n1: number, n2: number, cb: { (result: number): void }) {
  const result = n1 + n2;
  cb(result);
}
 




Any❤️

202111300742769

TypeScript不做任何的类型检查https://www.typescriptlang.org/play?q=139#example/any,让代码跟原来的JS一样,官网给出一个一很好的例子就是json解析。

// A good case for any is JSON parsing:

const myObject = JSON.parse("{}");

// Any declares to TypeScript to trust your code as being
// safe because you know more about it. Even if that is
// not strictly true. For example, this code would crash:

myObject.x.y.z;

另外一个例子,不做类型检查

function swap(x: [number, string]): [string, number] {
  return [x[1], x[0]];
}

const x: [any, any] = [1, 2];
swap(x);

unknown❤️

TIP

unknown类型相比any会做类型检查

let userInput: unknown;
let username: string;

userInput = 5;
// error unknown会做类型检查
//username = userInput;
userInput = "Aeroxian";
// 不能将类型“unknown”分配给类型“string”
//username = userInput;

// 需要用if来做类型推断⭐
if (typeof userInput === "string") {
  username = userInput;
}

 










 
 
 

使用另外一个例子

// ============= Your Code Here =============
type Push<T extends unknown[], U> = [...T, U];

// ============= Use Age ====================
const a: Push<["1", 2, "3"], boolean> = ["1", 2, "3", true];

// ============= output ====================
console.log(a); // [ '1', 2, '3', true ]

never

should never happern

告诉调用者,这个方法从不返回值

function generateError(msg: string, code: number): never {
  throw { msg, code };
}

generateError("Something Error", 500);