0

I would like to create an intersection type, which consists of a constructor signature and some other type.

type CustomMixer<T1, T2> = (new (...args: any[]) => T1) & T2

Generelly I need this to annotate the return type of a function, which sets some static methods to a Class(Function), like Object.assign(MyCtorFn, staticMethods)

TypeScript allows to create such types, return it, but I can't then initialize the type with the new keyword.

const MyType: CustomMixer<Foo, Bar> = someFactoryFunction()
const x = new MyType()

Cannot use 'new' with an expression whose type lacks a call or construct signature.

But, if CustomMixer intersection consists of a call signature and other type, then everything works as expected.

type CustomMixer<T1, T2> = ((...args: any[]) => T1) & T2
const MyType: CustomMixer<Foo, Bar> = someFactoryFunction()
MyType.| // Autocompletion for T2 works
const x = MyType()
x.|// Autocompletion for T1 works

Here is the link to TS Playground

Is it possible to make the first example work? Thank you.

1 Answer 1

1

You can do this:

type CustomMixer<T1, T2> = T1 & T2;

function CustomMixerFactory<T1, T2>(): CustomMixer<T1, T2> {
    // Mimic typed return
    return null as CustomMixer<T1, T2>;
}

const MyType = CustomMixerFactory<typeof Foo, Baz>();

MyType.isBaz(); // fine
let myType = new MyType(); // fine
myType.isFoo(); // fine
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, with the solution I even better undestand the type system in TypeScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.