typescript - TS 不提示允许的值,但可以正常工作
问题描述
我有两个接口,一个函数重载。我想如果通过就返回string[]
,如果通过就First
返回,并且返回不是传递值。下面的代码工作正常,但我的智能感知没有暗示允许的类型。(只有当我添加超载时)number[]
Second
<T>
代码
type First = { type: 'first'; data: string };
type Second = { type: 'second'; data: number };
function func<T>(): Array<T>;
function func(value: First): Array<string>;
function func(value: Second): Array<number>;
function func(value?: First | Second) {
if (value === undefined) return [];
if (typeof value === 'number') return ['qwe'];
return [1, 2, 3];
}
const a = func({ type: 'second', data: 123 });
const b = func({ type: 'first', data: "qwe" });
func({ data: 2, type: ''}) // here i can use only 'Second', but ts still hint only for 'First'
解决方案
@Micah Zoltu给我写信说:
重载往往会出现问题。不幸的是,即使有一个通用的,你仍然不能完全得到你想要的自动完成。
我决定修复它,只需添加带有后缀“T”的新功能。它可以按预期工作,但需要使用其他功能。
type First = { type: 'first'; data: string };
type Second = { type: 'second'; data: number };
function func(value: First): Array<string>;
function func(value?: Second): Array<number>;
function func(value?: First | Second) {
if (value === undefined) return [];
if (typeof value === 'number') return ['qwe'];
return [1, 2, 3];
}
function funcT<T = any>(): Array<T> {
return func() as any;
}
const a = func({ type: 'second', data: 123 }); // number[]
const b = func({ type: 'first', data: "qwe" }); // string[]
const c = funcT(); // any[]
const d = funcT<boolean>(); // boolean[]
推荐阅读
- php - HTTP_ORIGIN/HTTP_REFERER 的最佳替代方案是什么
- mysql - 如何在 DigitalOcean 的托管 MYSQL 数据库中更改时区?
- http - 在 TCP 探测和 HTTP 探测之间进行选择以了解 Kubernetes 中的活跃性和就绪性
- python - 重新网格化 nc 文件:Nctoolkit to_latlon 错误
- php - 如何防止发布重复值?
- html - 在使用 nth-of-type 和 first-of-type 时需要帮助
- python - 我无法通过 selenium 加载我的 chrome 配置文件
- angular - 角度/图形和 CORS
- rust - Rust:如何将 Entry API 与拥有的数据结合起来?
- python - 当我不使用任何全局变量时如何更新函数的返回值?