【问题标题】:Initializing TypeScript objects only with their class-specific properties using partials仅使用部分特定于类的属性初始化 TypeScript 对象
【发布时间】:2020-05-12 00:50:01
【问题描述】:

考虑以下示例:

const assign = <T, K extends keyof T>(...args: T[]): T =>
    args.reduce((result, current) =>
        (Object.keys(current) as K[]).reduce((target, key) => {
            target[key] = current[key];
            return target;
        }, result)
        , args[0]);

class Base {
    str1: string = '';
    str2: string = '';

    constructor(data: Partial<Base>) {
        assign(this, data);
    }
}

class Derived extends Base {
    str3: string = '';

    constructor(data: Partial<Derived>) {
        super(data);
        Object.assign(this, data);
    }
}

const derivedObj = new Derived({ str1: 'text', str3: 'new prop' })
const baseObject = new Base(derivedObj);

console.log(baseObject);
// Outputs:
// Data { "str1": "text", "str2": "", "str3": "new prop" } 

基类包含的属性少于派生类。基类构造函数接受Partial&lt;Base&gt;,它也与Partial&lt;Derived&gt; 类型兼容。这会导致在传递 Partial&lt;Derived&gt; 类型的对象时将无关的属性分配给基类对象。

有没有办法仅使用其类特定属性(strstr2而不是 str3)初始化基类对象?

PS:在 GitHub 和这里有很多看似相似的讨论。到目前为止,我还没有找到任何可以解决这个确切问题的方法。

【问题讨论】:

    标签: typescript typescript-types


    【解决方案1】:

    这行得通:

    const assign = <T, K extends keyof T>(...args: T[]): T =>
        args.reduce((result, current) =>
            (Object.keys(args[0]) as K[]).reduce((target, key) => {
                if (current[key] !== undefined) target[key] = current[key];
                return target;
            }, result)
        , args[0]);
    

    看到这个playground

    【讨论】:

    • 谢谢你,看着你的代码,我意识到我是如此接近。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    相关资源
    最近更新 更多