typescript - 推断函数返回类型,了解一个属性的值

标签 typescript typescript-generics

有办法吗?我知道,我可以 if/else 或切换我的“type”属性来获取特定的接口(interface)。但是我可以用函数(或方法)的返回值来制作类似的东西吗?

interface test1 {
    type: 'test1'
}

interface test2 {
    type: 'test2'
}

type unType = test1 | test2;

//i know property "type"'s value
//can i somehow use this information to infer specific type (test1 or test2)
function whichType<T>(typeValue): T {

    return null;
}

const tt1 = whichType<unType>('test1');// should be interface test1
const tt2 = whichType<unType>('test2');// should be interface test2

最佳答案

您可以按照 TJ Crowder 的建议使用重载,如果您只有几个接口(interface),这可能是最好的解决方案,因为编写理解很简单。

更通用的解决方案是使用 Extract 条件类型根据传入的字符串提取类型:

interface test1 { type: 'test1' }

interface test2 { type: 'test2' }

type unType = test1 | test2;

function whichType<K extends unType['type']>(typeValue: K): Extract<unType, {type: K}> {
    return null!;
}

const tt1 = whichType('test1'); // test1
const tt2 = whichType('test2'); // test2

可以构建适用于任何联合的解决方案,但它要求您使用函数柯里化(Currying),因为 typescript 不支持部分类型参数推断:

function whichType<T extends { type: string}>() {
    return function <K extends T['type']>(typeValue: K): Extract<T, {type: K}> {
        return null!;
    }
}

const tt1 = whichType<unType>()('test1'); // test1
const tt2 = whichType<unType>()('test2'); // test2

关于typescript - 推断函数返回类型,了解一个属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55989937/

相关文章:

typescript - 如何修复 "Type ' BaseCtor' 不可分配给类型 'T'“同时使用带有默认参数的泛型

typescript - 根据先前的参数推断参数的类型

typescript - 在已安装的依赖项中排除 @types 类型

angular - 剑道 UI Angular : (SystemJS) Unexpected token <

TypeScript 安全函数组合

typescript - 类方法的条件返回类型取决于构造函数中的选项

typescript - Angular 2错误提供的参数与调用目标的任何签名都不匹配

javascript - typescript 并将对象转换为字符串

typescript - 为什么 Typescript 箭头函数泛型与命名函数泛型的工作方式不同

具有多个条件的 Typescript 条件映射类型