【问题标题】:How to copy the structure of one generic to another generic, replacing the original values with custom values?如何将一个泛型的结构复制到另一个泛型,用自定义值替换原始值?
【发布时间】:2021-09-08 03:31:09
【问题描述】:

先阅读这个问题可能会有所帮助:How to copy the structure of one generic type to another generic in TypeScript?

给定以下输入类型:

interface InputType {
    age: number;
    surname: string;
}

我想要一个可以为上述输入生成以下输出类型的函数:

type OutputValue<T> = (val: T) => void;

interface OutputType {
    age: OutputValue<number>;
    surname: OutputValue<string>;
}

这个函数的签名是:

type OutputType<T> = {
    [k in keyof T]: OutputValue<T[k]>
}

type TransformationFunction<Input, Output extends OutputType<Input>> = (input: Input) => Output;

上面的类型签名将确保输出是类型安全的。这意味着我可以使用智能感知来正确检索output.surname 函数(例如)。

棘手的部分是以类型安全的方式返回正确的数据结构。

这是我的尝试:

const transformString = (stringValue: string) => {
    return (val: string) => {
        // some code processing val
    }
}

const transformationFunction = function<Input, Output extends GenericMap<Input>>(input: Input): Output {
    const keys = Object.keys(input) as Array<keyof Input>;

    return keys.reduce((output: Output, key: keyof Input) => {
        const inputValue = input[key];

        if (/*typeguard*/ isString(inputValue)) {
            return transformString(inputValue); // typescript compiler complains
        }
        else if ( /*typeguard*/ isNumber(inputValue)) {
            return transformNumber(inputValue); // similar function to above + typescript complains
        }
        else {
            throw new Error("No transform");
        }
    }, {} as Output)
}

如何将自定义值应用到输出对象?

Playground of actual problem

【问题讨论】:

  • 有点不清楚您的实际设置是什么。或许提供playground 链接?

标签: javascript typescript typescript-generics


【解决方案1】:

使用for循环代替reduce,这成为可能:

(output[key] as unknown as OutputValue<string>) = transformString(inputValue)

而不是 return transformString(inputValue) 期望 OutputValue&lt;Input[keyof Input]&gt;

Playground link

【讨论】:

  • 谢谢,我去看看。也用我的游乐场更新 OP
  • 越来越近,但我的操场仍然有问题
  • 好的,开始工作了 :) 您的解决方案效果很好,但它有一个重大缺陷。由于对OutputValue 的弱转换,在创建output 对象时没有类型安全。例如。我可以轻松地将字符串值转换为数字输出类型
猜你喜欢
  • 2021-09-08
  • 2021-09-07
  • 1970-01-01
  • 2014-01-07
  • 2020-12-05
  • 1970-01-01
  • 2021-06-09
  • 1970-01-01
  • 2014-08-02
相关资源
最近更新 更多