Latest Update (2023)
Recently, I presented a talk on the topic of integrating tsc
with JSDoc, addressing not only this question but several related issues:
I also introduced a package to simplify the tsconfig
setup:
- https://npmjs.org/jswt
npx jswt init
The Original Question Posed
My current challenge involves using tsc
with plain Vanilla JS and struggling with defining the type for a function.
It appears that the solution should be straightforward:
/** @type PersonGreet */
person.greet = function greet(other) {
return `Hello ${other.name}, my name is ${person.name}!`;
};
Note: The usage of /** @type PersonGreet */
is indeed correct. The issue at hand seems to be a bug in tsc
. Various valid workarounds are discussed in the answer below.
Simplified Test Scenario
While one might consider refactoring this code to utilize classes or prototypes, it effectively illustrates the problem at hand.
Repository: https://github.com/BeyondCodeBootcamp/hello-tsc
"use strict";
/**
* @typedef {Object} Person
* @property {String} name
* @property {PersonGreet} greet
*/
/**
* @typedef {Function} PersonGreet
* @param {Person} other
* @returns {String}
*/
let Person = {};
/**
* Creates a person
* @param {Object} p
* @param {String} p.name
* @returns {Person}
*/
Person.create = function (p) {
let person = {};
person.name = p.name;
/////////////////////////////////////////////////////////////////////////////////
//
// error TS7006: Parameter 'other' implicitly has an 'any' type. <======= WRONG!
//
/////////////////////////////////////////////////////////////////////////////////
/** @type PersonGreet */
person.greet = function greet(other) {
return `Hello ${other.name}, my name is ${person.name}!`;
};
return person;
};
module.exports = Person;
Misidentified as "any"
Upon running tsc
for verification, an error concerning implicit any types is reported:
tsc -p jsconfig.json
person.js:28:33 - error TS7006: Parameter 'other' implicitly has an 'any' type.
28 person.greet = function greet(other) {
~~~~~
Found 1 error in person.js:28
How to Proceed?
In my view, this issue seems like a flaw within tsc
... However, considering this is fundamental JavaScript knowledge, there must be a way to specify a function's type, right?
What annotation should be used to declare the function's type? Or is it possible that tsc
, tsserver
, or typescript
cannot handle such basic JavaScript concepts?