TypeScript avoid TS2749 and avoid using typeof on classes imported using require (run using bun)

61 views Asked by At

The code

Given a file named foo.ts containing a class:

export default class Foo { name = 'bar' }

Given a program using this module:

const Foo = require('./foo').default
function logFoo(foo: Foo) { console.log(foo) }
logFoo(new Foo)

The program runs perfectly using bun:

bun test.ts

The problem

It generates a TypeScript "error TS2749: 'Foo' refers to a value, but is being used as a type here. Did you mean 'typeof Foo'?", on command line and into my WebStorm IDE.

Why that, and how to deal with it ?

Your answer should take care of these constraints:

  • I know that replacing the require by import Foo from './foo' will remove the TS error: I just don't want to use import.
  • I know declaring the parameter of the function like this: foo: typeof Foo will remove the TS error: I just don't want to use typeof, I want my function parameters to be declared the same way for a required class type, a local class type and an imported class type.

Similar problem on a shorter example

I got the same problem with it, into a single program file:

class Foo { name = 'bar' }
const It = Foo
function logFoo(foo: It) { console.log(foo) }
logFoo(new Foo)

The parameter of type It throws a TS2749, but the parameter of type Foo is OK. Why and how to deal with it?

It is the same problem, without considerations about different module standards compatibility.


Working cases

No TS2749 for these variants:

const Foo = require('./foo').default
function logFoo(foo: typeof Foo) { console.log(foo) }
logFoo(new Foo)

or:

import Foo from './foo'
function logFoo(foo: Foo) { console.log(foo) }
logFoo(new Foo)

But I want it to work with require and without typeof.

No TS2749 for these "bonus case" variants:

class Foo { name = 'bar' }
const It = Foo
function logFoo(foo: typeof It) { console.log(foo) }
logFoo(new Foo)

or:

class Foo { name = 'bar' }
const It = Foo
function logFoo(foo: Foo) { console.log(foo) }
logFoo(new Foo)

But I want it to work with It and without typeof.

0

There are 0 answers