In a JavaScript project, how can I add typed config objects that I can pass into a constructor and that work with VSCode code completion?
Here is a screenshot from the Three.js library that provides the functionality I am referring to. I am trying to replicate this in my own JavaScript project.
Here is what I tried. Both files are in the same directory. I am using Webpack as a bundler, no typescript configuration whatsoever. The .d.ts file appears to get ignored.
What do I need to do to get this to work? Add a config file? Change Webpack setup?
// Person.js
export class Person {
constructor(parameters) {
this.name = parameters.name;
this.age = parameters.age;
}
}
// Person.d.ts
export interface PersonParameters {
name: string,
age?: number
}
export class Person {
constructor(parameters: PersonParameters);
}
TypeScript can be a hassle to set-up for newcomers and if you're only going to use it for type declarations, it's really not as worth it. So you could try plain old JSDoc:
/**
* @typedef {object} PersonConfig
* @prop {string} name
* @prop {number} age
*/
/**
* A human being
*/
export class Person {
/*
* Mimics the birth of a new person
* @param {PersonConfig} parameters
*/
constructor(parameters) {
this.name = parameters.name;
this.age = parameters.age;
}
}
I tried your example and it works well as source files. So I guess you are asking how to ship the definitions so that the end-users can use them. There are several ways to do it.
Create d.ts
files and use CopyWebpackPlugin to copy them to the dist folder. You can either create a single d.ts
file or create one for each js file, an entry point like index.d.ts
might be needed.
Rewrite the library using TypeScript😄, and generate typings using ts-loader
or tsc
directly, by setting declaration
and outDir
in tsconfig.json
.
It's also possible to create a pr to DefinitelyTyped so users can install typings separately via @types/<your-lib>
like what three.js does. But since it's your own library that should be overkilled.
Reload VS Code if it doesn't take effect immediately after the definitions are copied to the target folder.