TS 速记
function compare(a: string, b: string): -1 | 0 | 1 {
return a === b ? 0 : a > b ? 1 : -1;
}declare function handleRequest(url: string, method: “GET” | “POST”): void;
const req = { url: “https://example.com”, method: “GET” };
handleRequest(req.url, req.method);
// Argument of type ‘string’ is not assignable to parameter of type ‘”GET” | “POST”’.// Change 1:
const req = { url: “https://example.com”, method: “GET” as “GET” };//声明时就加上类型断言
// Change 2
handleRequest(req.url, req.method as “GET”);
const req = { url: “https://example.com”, method: “GET” } as const;//把整个对象作为一个类型字面量
handleRequest(req.url, req.method);几种特殊类型:
函数
调用签名
构造签名
泛型约束
函数重载
最后更新于