首页 > 解决方案 > 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'

TS播放

标签: typescripttypescript-typingstypescript-generics

解决方案


@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[]

TS播放


推荐阅读