How do I resove this Typescript assigning error?

Viewed 25
const widgett = {};
class Widget {
  constructor() {
    console.log('wi');
  }
}
function Widget2() {
  console.log('wi');
}
// const w = new Widget();

function logDec(factory: () => widgett):(() => widgett) {
  return () => {
    console.log(123);
    factory();
  };
}

The factory is a function that returns a Widget object, but it tells me to put a type instead of a value. But a function return a value not a type right?

FYI error message: 'widgett' refers to a value, but is being used as a type here. Did you mean 'typeof widgett'?(2749)

1 Answers

The function returns a value (an expression), but when denoting types in TypeScript syntax, you may only use types, not JavaScript expressions.

But since you aren't returning anything from inside the callback, you shouldn't be noting any return value at all.

function logDec(factory: () => void): () => void {

If you meant for the callback to return a value, you'll have to add return when calling factory.

function logDec(factory: () => Widget): () => Widget {
    return () => {
        console.log(123);
        return factory();
    };
}
const w = new Widget();
logDec(() => w);
Related