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);
}
CodePudding user response:
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;
}
}
CodePudding user response:
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 singled.ts
file or create one for each js file, an entry point likeindex.d.ts
might be needed.Rewrite the library using TypeScript