Home > Net >  Is there a way to type this correctly in TypeScript?
Is there a way to type this correctly in TypeScript?

Time:11-27

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.

CodePudding user response:

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.

CodePudding user response:

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
  • Related