Typescript: In JS, assertions imported via commonjs have bogus error

Created on 7 May 2020  路  5Comments  路  Source: microsoft/TypeScript

Code

// @filename: declares.d.ts
// this is the declaration for 'assert' from @types/node
export function art(value: any, message?: string | Error): asserts value;

// @filename: test.js
const { art } = require('./declares')
let x = 1
art(x)

Expected behavior:
No error.

Actual behavior:
Error: "Assertions require every name in the call target to be declared with an explicit type annotation."

There is no error when using ES imports:

// @filename: test2.js
import { art } from './declares'
let x = 1
art(x)
Bug Fix Available

Most helpful comment

I ran into this today when updating @types/node and using require('assert') from node core.

I fixed this with

/** @type {import('assert')} */
const assert = require('assert')

Is it possible for the type definition of require in TypeScript itself to return function require(module: T): import<T> ?

All 5 comments

Repros since 3.7, when we introduced asserts.

My hot take is that this is a bogus error almost everywhere you could get it...

I ran into this today when updating @types/node and using require('assert') from node core.

I fixed this with

/** @type {import('assert')} */
const assert = require('assert')

Is it possible for the type definition of require in TypeScript itself to return function require(module: T): import<T> ?

The problem is that symbols imported via require aren't actually aliases, so they don't get resolved in getTypeOfDottedName.

I prototyped a solution at the branch alias-for-require. It fixes this example, but is woefully incomplete everywhere else. It still needs:

  1. More complete handling of object literal syntax, which has way more options than the import syntax.
  2. Handling of un-destructured require.
  3. Rewrite of d.ts emit code.
  4. Replacement and removal of all the special-case fake-alias code elsewhere.
  5. Anything else I don't know about right now.

@weswigham you might be interested in this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

seanzer picture seanzer  路  3Comments

Roam-Cooper picture Roam-Cooper  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments

siddjain picture siddjain  路  3Comments