Skip to main content

类型断言

类型断言:有些情况下,TS 推导出来的类型并不是你想要的(比如未推导出类型或者期望类型是推导类型的子类型时),可以用类型断言来明确地声明其类型:

const foo: string | number = "this is a string";

const fooLen = (foo as string).length;
// or const fooLen = (<string>foo).length;

as const

const obj = { a: 1, b: "2" };

上面的代码显然 obj 的类型会被自动推导成:

interface Obj {
a: number
b: string
}

const obj = { a: 1, b: '2' } as const
interface Obj {
a: 1
b: '2'
}