I have the following code snippet, my question is how do I keep the literal type information of knowLiteral without having to spell out the type like I am doing right now?
// @ts-check
/**
* @typedef {Readonly<Record<string, string>>} ReadonlyStringRecord
*/
/**
* @template {ReadonlyStringRecord} T
*/
class Main {
/**
* @param {T} knowLiteral
*/
constructor(knowLiteral) {
/**
* @readonly
* @type {T}
*/
this.knowLiteral = knowLiteral;
}
}
// how not to have to write this?
/**
* @extends {Main<{
* this_is_know: '42'
* }>}
*/
class Main2 extends Main {
constructor() {
const knowLiteral = /** @type {const} */ ({ 'this_is_know': '42' });
super(knowLiteral);
}
testFunc() {
//this should (and does) error.
let x = this.knowLiteral.this_is_not_defined;
}
}
To keep the literal type information of knowLiteral without manually spelling out the type when extending the Main class, you can utilize TypeScript’s ability to infer the type from a constant object. You can do this by defining the literal as a const object and letting TypeScript infer the type automatically.
prabhat verma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.