英文:
How to type keyof instace in JSDOC similarily to TS?
问题
如何在JavaScript(JSDOC)中像TypeScript一样键入实例的关键字?
TS很好:
const a1 = new Car('Audi A1', 4, Power.solar);
const a380 = new Plane('Airbus A380', 800, 4);
function showProperty<T>(thing: T, prop: keyof T) {
console.log(`${String(prop)}:`, thing[prop]);
}
showProperty(a1, 'power');
showProperty(a380, 'engines');
完整的TS代码链接: 点击此处
但我不知道如何在jsdoc中实现:
const a1 = new Car('Audi A1', 4, 'petrol');
const a380 = new Plane('Airbus A380', 800, 4);
/**
* @param {Thing} thing
* @param {keyof Thing} prop
*/
function showProperty(thing, prop) {
console.log(`${String(prop)}:`, thing[prop]);
}
showProperty(a1, 'capacity'); // 我想在这里看到 "power" 属性...!
showProperty(a380, 'capacity'); // 我想在这里看到 "engines" 属性...!
英文:
How can I type keyof instance in Javascript (JSDOC) similarily to Typescript?
TS is just fine:
const a1 = new Car('Audi A1', 4, Power.solar);
const a380 = new Plane('Airbus A380', 800, 4);
function showProperty<T>(thing: T, prop: keyof T) {
console.log(`${String(prop)}:`, thing[prop]);
}
showProperty(a1, 'power');
showProperty(a380, 'engines');
link to full TS code
but I don't know how to do it with jsdoc:
const a1 = new Car('Audi A1', 4, 'petrol');
const a380 = new Plane('Airbus A380', 800, 4);
/**
* @param {Thing} thing
* @param {keyof Thing} prop
*/
function showProperty(thing, prop) {
console.log(`${String(prop)}:`, thing[prop]);
}
showProperty(a1, 'capacity'); // I want to see the "power" property here...!
showProperty(a380, 'capacity'); // I want to see the "engines" property here...!
link to full JS code
答案1
得分: 2
使用TypeScript中的JSDoc注释,您可以使用@template
标记为函数声明一个类型参数。这类似于TypeScript使用尖括号(<T>
)定义类型参数的语法。
/**
* @template T
* @param {T} thing
* @param {keyof T} prop
*/
function showProperty(thing, prop) {
console.log(`${String(prop)}:`, thing[prop]);
}
链接到修改后的JS代码
英文:
With JSDoc annotations in TypeScript, you can use the @template
tag to declare a type parameter for the function. This is similar to the TypeScript syntax of using angle brackets (<T>) to define a type parameter.
/**
* @template T
* @param {T} thing
* @param {keyof T} prop
*/
function showProperty(thing, prop) {
console.log(`${String(prop)}:`, thing[prop]);
}
VSCode and other code editors should now be able to see all the properties
Link to modified JS code
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论