ts-check-jsdoc-experiment
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUse @ts-check and JSDoc to Experiment with TypeScript
使用@ts-check和JSDoc尝试TypeScript
Overview
概述
You can add TypeScript type checking to JavaScript files without converting them to TypeScript. Use at the top of a JS file and JSDoc annotations to add types. This lets you experiment with TypeScript gradually without committing to the full conversion.
@ts-check无需将JavaScript文件转换为TypeScript,即可为其添加TypeScript类型检查功能。在JS文件顶部添加并使用JSDoc注解来定义类型,这样你就可以逐步尝试TypeScript,而无需完全转换代码。
@ts-checkWhen to Use This Skill
适用场景
- Experimenting with TypeScript
- Gradually migrating JavaScript
- Adding types to JS files
- Teams learning TypeScript
- Validating JavaScript with types
- 尝试使用TypeScript
- 逐步迁移JavaScript
- 为JS文件添加类型
- 团队学习TypeScript
- 为JavaScript进行类型校验
The Iron Rule
核心规则
Use and JSDoc to add TypeScript checking to JavaScript files without full conversion.
@ts-check使用和JSDoc为JavaScript文件添加TypeScript检查,无需完全转换代码。
@ts-checkExample
示例
javascript
// @ts-check
/**
* @param {string} name
* @param {number} age
* @returns {string}
*/
function greet(name, age) {
return `Hello ${name}, you are ${age}`;
}
greet('Alice', 30); // OK
greet('Alice', '30'); // Type error!
/** @type {string[]} */
const names = ['Alice', 'Bob'];
/** @typedef {{ x: number, y: number }} Point */
/** @type {Point} */
const point = { x: 1, y: 2 };javascript
// @ts-check
/**
* @param {string} name
* @param {number} age
* @returns {string}
*/
function greet(name, age) {
return `Hello ${name}, you are ${age}`;
}
greet('Alice', 30); // OK
greet('Alice', '30'); // Type error!
/** @type {string[]} */
const names = ['Alice', 'Bob'];
/** @typedef {{ x: number, y: number }} Point */
/** @type {Point} */
const point = { x: 1, y: 2 };Reference
参考资料
- Effective TypeScript, 2nd Edition by Dan Vanderkam
- Item 80: Use @ts-check and JSDoc to Experiment with TypeScript
- Dan Vanderkam所著《Effective TypeScript(第二版)》
- 第80条:使用@ts-check和JSDoc尝试TypeScript