解决字面量类型推断错误的四种方式
declare function handleRequest(url: string, method: "GET" | "POST"): void;
const req = { url: "https://www.baidu.com", method: "GET" }
handleRequest(req.url, req.method);
报错如下
方式一:对象属性使用类型断言
declare function handleRequest(url: string, method: "GET" | "POST"): void;
const req = { url: "https://www.baidu.com", method: "GET" as "GET" };
handleRequest(req.url, req.method);
方式二:传参使用类型断言
declare function handleRequest(url: string, method: "GET" | "POST"): void;
const req = { url: "https://www.baidu.com", method: "GET" };
handleRequest(req.url, req.method as "GET");
方式三:对象使用类型断言
declare function handleRequest(url: string, method: "GET" | "POST"): void;
const req = { url: "https://www.baidu.com", method: "GET" } as const;
handleRequest(req.url, req.method);
方式四:对象属性使用变量,变量使用字面量类型
declare function handleRequest(url: string, method: "GET" | "POST"): void;
const method: "GET" | "POST" = "GET";
const req = { url: "https://www.baidu.com", method };
handleRequest(req.url, req.method);