【TypeScript】解决字面量类型推断错误的四种方式

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);

参考

literal-inference
unit-types

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
TypeScript具有丰富的类型系统,可以帮助开发者在编码过程捕获错误、提供代码补全和自动提示等功能。以下是一些常见的 TypeScript 类型: 1. 原始类型: - boolean: 布尔类型,只能是 true 或 false。 - number: 数字类型,包括整数和浮点数。 - string: 字符串类型。 - null 和 undefined: 分别表示空值和未定义值。 2. 数组类型: - 基本数组类型:例如 number[] 表示数字数组,string[] 表示字符串数组。 - 泛型数组类型:使用泛型语法定义特定类型的数组,例如 Array<number> 表示数字数组。 3. 元组类型: - 元组是固定长度和特定类型的数组。 - 例如 [string, number] 表示包含一个字符串和一个数字的元组。 4. 对象类型: - 对象类型可以使用字面量语法定义,例如 { name: string, age: number } 表示一个具有 name 和 age 属性的对象。 - 也可以使用接口(interface)或类(class)定义对象类型。 5. 函数类型: - 函数类型包括参数的类型和返回值的类型,例如 (a: number, b: number) => number 表示接收两个数字参数并返回一个数字的函数类型。 6. 枚举类型: - 枚举用于定义一组命名的常量值。 - 例如 enum Color { Red, Green, Blue } 定义了一个颜色的枚举类型,可以通过 Color.Red、Color.Green 等访问枚举值。 除了以上类型TypeScript 还支持联合类型、交叉类型类型别名、类型推断和泛型等高级特性,可以更灵活地应对各种编程场景。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值