How could a TypeScript interface be usable when it is describing both an object and a function at the same time?

Viewed 28

I'm using TypeScript 4.2.4. Say I have the following TypeScript code.

// perfectly legal syntax
interface MyInterface {
    attr1: number;
    (): number;
}

// Compilation error: Type '{ attr1: number; }' provides no match for the signature '(): number'
let x: MyInterface = {
    attr1: 1
};

// Compilation error: Property 'attr1' is missing in type '() => number' but required in type 
let y: MyInterface = () => {
    return 1;
}

Did I just create an unusable interface? How such interface can be used?

Please don't mind the example not making any sense. I'm asking this question to learn the language.

1 Answers

I'm not sure if there is a syntax which would allow you to define it directly, but I was able to get it to compile this way:

interface MyInterface {
    attr1: number;
    (): number;
}

const x = () => 1
x.attr1 = 10

const y: MyInterface = x

Since functions are actually just some type of Object in JavaScript, this is perfectly legal. It is callable if you call it (y()) but it can also have additional properties on it (y.attr1)

Related