三、枚举与断言:
断言:有时候你会比
TS更加明确一个变量的类型, 这个时候,可以使用类型断言来制定更具体的类型。
枚举:定义一组命名常量,他描述一个值,这个值可以是这些命名常量中的任意一个。
-
枚举(enum):
enum SexType { BOY, GIRL, } let user = { name: "typescript", sex: 1, }; console.log(SexType.GIRL); -
断言:
function fun(arg: boolean): string | number { return arg ? "我就干" : 2030; } let res = fun(true) as string; // res = 1232; // 这是错误 res = "typescript"; console.log(res); -
非空断言:
const el: HTMLDivElement = document.createElement(".hd") as HTMLDivElement; const aLink = document.querySelector("#hd") as HTMLLinkElement; 或 const el: HTMLDivElement = document.createElement(".hd")!; -
class构造函数需要的强制断言:
class Hd { el: HTMLDivElement; constructor(el: HTMLDivElement) { this.el = el; } html() { return this.el.innerHTML; } } const el = document.querySelector(".xj") as HTMLDivElement; new Hd(el);