使用条件类型提取返回值类型

问题描述

我试图弄清楚条件类型的工作原理,但似乎我没有正确理解某些东西。

假设我有一个 API 以特定格式返回一些数据:

type SchemaOne = {
    [key: string]: {
        schemaOnePropOne: string;
        schemaOnePropTwo: string;
    };
}

type SchemaTwo = {
    [key: string]: {
        schemaTwoPropOne: string;
        schemaTwoPropTwo: string;
    };
}

我需要将它们转换为这种格式:

type TransformedSchemaOne = {
    title: string;
    schemaOnePropOne: string;
    schemaOnePropTwo: string;
}
type TransformedSchemaTwo = {
    title: string;
    schemaTwoPropOne: string;
    schemaTwoPropTwo: string;
}

所以我可以使用这样的函数

const transformSchemas = <T extends Schemas>(obj: T): ExtractReturnedType<T>[] => {
    const keys = Object.keys(obj);
    const newObj = keys.map(key=> ({title: key,...obj[key]}))
    return newObj;
}

这会给我

[{ "title": "title","schemaOnePropOne": "一","schemaOnePropTwo": "两个" }]

现在我想为该函数引入类型,因此我从一个 API 创建了模式的联合

type Schemas = SchemaOne | SchemaTwo;

提取返回值的条件类型:

type ExtractReturnedType<S> = S extends SchemaOne ? TransformedSchemaOne : S extends SchemaTwo ? TransformedSchemaTwo : never;

当我使用特定模式进行测试时,这似乎有效:

// no type errors 
const testOne:ExtractReturnedType<SchemaOne>[] = [{
    schemaOnePropOne: 'string;',schemaOnePropTwo: 'string;',title: 'string;',}]
// no type errors
const testTwo:ExtractReturnedType<SchemaTwo>[] = [{
    schemaTwoPropOne: 'string;',schemaTwoPropTwo: 'string;',}]

但是当我创建类型化函数时,我得到了类型错误

const transformSchemas = <T extends Schemas>(obj: T): ExtractReturnedType<T>[] => {
    const keys = Object.keys(obj);
    const newObj = keys.map(key=> ({title: key,...obj[key]}))

    // Type '({ schemaOnePropOne: string; schemaOnePropTwo: string; title: string; } | { schemaTwoPropOne: string; schemaTwoPropTwo: string; title: string; })[]' is not assignable to type 'ExtractReturnedType<T>[]'.
    // Type '{ schemaOnePropOne: string; schemaOnePropTwo: string; title: string; } | { schemaTwoPropOne: string; schemaTwoPropTwo: string; title: string; }' is not assignable to type 'ExtractReturnedType<T>'.
    // Type '{ schemaOnePropOne: string; schemaOnePropTwo: string; title: string; }' is not assignable to type 'ExtractReturnedType<T>'.(2322)
    return newObj;
}

Link to playground with code

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...