1

How should I write a function fn to match the type DescribableFunction

type DescribableFunction = {
    description: string;
    (arg: string): number;
    new (someArg: number): string
};
function doSomething(fn: DescribableFunction) {
    console.log(`${fn.description} returned ${fn('lorem')} or ${new fn(1)}`);
}

const fn: DescribableFunction = function (arg: string) {

}

doSomething(fn)

1 Answer 1

0

It is impossible without type assertions.

Due to historical reasons, some constructors in JavaScript can be invoked with new keyword or as a regular functions, for instance Date or Array.

These constructors are built in. You are not allowed to build such constructor without type assertions. However, you can get rid of new (someArg: number): string in DescribableFunction and just to add description property:

type DescribableFunction = {
  description: string;
  (arg: string): number;
};

function doSomething(fn: DescribableFunction) {
  console.log(`${fn.description} returned ${fn('lorem')} or ${new fn(1)}`);
}

const fn: DescribableFunction = function (arg: string) {
  return 42
}
fn.description = ''

doSomething(fn)

Here you can find more explanation about typing static property of functions.

Here you can find related question/answer

P.S.Please keep in mind that you can create custom constructor with similar behavior in pure js (see new.target)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. I asked this question because I found similar construction in TypeScript documentation link in Construct Signatures section ` interface CallOrConstruct { new (s: string): Date; (n?: number): number; } `
You should use type assertion as to make it work in ts

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.