Typescript: In JS, `object` is treated as 'any'

Created on 13 Jul 2018  路  8Comments  路  Source: microsoft/TypeScript

TypeScript Version: 3.0.0-dev.20180711

Code

/** @typedef {object} T */
/** @type {T} */
const x = 0;

Expected behavior:

Error at x: 0 is not an object.

Actual behavior:

No error.

Awaiting More Feedback JSDoc JavaScript lib.d.ts Suggestion checkJs

All 8 comments

I think this is a result of Object/object being treated as any. For example, /** @typedef {{}} T */ produces an error.

In getTypeFromTypeNode, we have:

case SyntaxKind.ObjectKeyword:
    return node.flags & NodeFlags.JavaScriptFile ? anyType : nonPrimitiveType

This was originally added in #17082. We could revisit this decision, but case-insensitive primitives and Object as any are good decisions in my opinion.

Solution may be to add a new type which is definitely the same as ts's object regardless of what kind of file it appears in.

Maybe type NonPrimitive = object in lib.d.ts?

Maybe. #35661 only applies when noImplicitAny: true though.

I鈥檇聽like if聽there聽was a聽way to聽use the聽object聽type in聽JSDoc without聽needing to聽enable聽noImplicitAny.

@ExE-Boss you can use the type NonPrimitive = object in one of your own d.ts files. Unfortunately, lots of existing JS code uses object to mean any or unknown, even projects like webpack that compile regularly with typescript.

Was this page helpful?
0 / 5 - 0 ratings