trusktr
trusktr

Reputation: 45454

Does TypeScript JSDoc-style typing have full power of regular types?

TypeScript is said to be "turing complete". Is the JSDoc-style typing as feature full as regular types? Can we do mapped types, conditional types, keyof, etc, and all the things of regular types?

Just curious, because I'd like to declare types for JS files that implement class-factory mixins and that define define functions that accepts objects and return classes generated from the object definition. The generated classes should have protected and private members, and the mixins should return classes with protected/private members.

I'd like to type these things without having to convert to .ts files, just keep the JS code as is.

Is it possible with JSDoc comments, to type such meta things like generated classes from object literal definitions and class-factory mixins, etc?

Upvotes: 4

Views: 1108

Answers (2)

Eri
Eri

Reputation: 90

I don't have enough reputation to add comment, but Ruby's answer is now outdated. You could do something like

/**
 * @template T
 * @typedef Parameters
 * A tuple of the types of the parameters of a function.
 * @type {(T extends (...args: infer U) => * ? U : never)}
 */
/** @type {Parameters<(a: string) => void>} */
const x; // has type [a: string]

Upvotes: 0

Ruby Tunaley
Ruby Tunaley

Reputation: 371

Not all types expressible in TypeScript can be represented in JSDoc. Example:

/**
 * @typedef Parameters
 * A tuple of the types of the parameters of a function.
 * @template T
 * @type {(T extends (...args: infer U) => * ? U : never)}
 */

Trying to use this type causes the TypeScript service to think that Paramaters<T> = any. This means that conditional types are not supported.

In general, you can figure out whether a type is supported in JSDoc by writing it and seeing whether the service gives up and just says it's any.

Upvotes: 1

Related Questions