TypeScript-04-字面量 type + 联合类型,类型自动推断返回值,as 运行时错误

58 阅读1分钟

总结:

  • let a: number 明确类型,
  • code: 1001|1002|1003 。code 不能赋值 1004
  • 类型推断:let a = 100 .已经明确了类型,后续不能赋值其他类型
  • any 谨慎使用 。
  • as 断言,无法避免运行是错误。对比 typeof instanceof

function padLeft(value: string, padding: string | number) {
  if (typeof padding === "number") {
    return Array(padding + 1).join(" ") + value;
  }
  if (typeof padding === "string") {
    return padding + value;
  }
  throw new Error(`Expected string or number, got '${padding}'.`);
}

function move(animal: Bird | Fish) {
  if (animal instanceof Bird) {
    animal.fly();
  } else {
    animal.swim();
  }
}


字面量: image.png

image.png

image.png

思考题:

image.png

code: 1001|1002|1003

image.png 解决:

image.png

类型推断

image.png

any 谨慎使用

image.png

类型断言 as

image.png

image.png