lemme
lemme

Reputation: 63

Is there a way to type this correctly in TypeScript?

I want to type such function in typescript:

(anyClass, somePropertiesObject) => newClassExtendingAnyClassWithPropsAddedFromTheObject

The purpose of the function is pretty simple, just take some class and some object as an argument and return new class extending supplied class, but with properties added from the second argument.

I have really hard time figureing out how to type this correctly. I would really appreciate help.

Upvotes: 3

Views: 691

Answers (2)

AndreyProgr
AndreyProgr

Reputation: 672

We should use Generics here:

type MergeFunction = <A, B>(objectA: A, objectB: B) => A & B;

const mergeObjects: MergeFunction = (objectA, objectB) => ({ ...objectA, ...objectB });

// Usage:
const result = mergeObjects({ a: 1 }, { b: 2 });
result.a; // 1
result.b; // 2

A - original object (or class, it looks like this does not matter in this particular case)

B - another object we want to megre with

A & B - TS type describing an object that contains properties from both A and B

TypeScript will automatically compute a type of the result (return value).

Upvotes: -1

Consider this example:

type AnyClass = new (...args: any[]) => any

const extend = <
    Class extends AnyClass, Obj extends Record<string, unknown>
>(AnyClass: Class, somePropertiesObject: Obj) => class _ extends AnyClass {
        props = somePropertiesObject

        constructor(...args: any[]) {
            super(args)
        }

    }

class Derived {
    name = 'Derived'
}
const obj = {
    age: 42
}

const Result = extend(Derived, obj);

const test = new Result()

test.name // string
test.props.age // number

AnyClass - represents a type of any constructor. I mean any function which can be called with new keyword. I have used this constraint in extend function since you expect first argument to be a class.

Obj - represents any object with string key and unknown value. Corresponds to second argument.

I have used props property in new class to store somePropertiesObject.

As you might have noticed, all properties of provided class and object are allowed to use in a result.

Upvotes: 2

Related Questions