Skip to content

Commit 90359de

Browse files
authored
init translation of type checking js files (#93)
1 parent 2b5e4a6 commit 90359de

File tree

1 file changed

+57
-76
lines changed

1 file changed

+57
-76
lines changed
Lines changed: 57 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,17 @@
11
---
2-
title: Type Checking JavaScript Files
2+
title: JavaScript 文件的类型检查
33
layout: docs
44
permalink: /zh/docs/handbook/type-checking-javascript-files.html
5-
oneline: How to add type checking to JavaScript files using TypeScript
5+
oneline: 如何使用 TypeScript 为 JavaScript 文件添加类型检查
66
---
77

8-
Here are some notable differences on how checking works in `.js` files compared to `.ts` files.
8+
以下是 `.js` 文件和 `.ts` 文件类型检查工作方式的一些显著差异。
99

10-
## Properties are inferred from assignments in class bodies
10+
## 属性从类体中的赋值推断
1111

12-
ES2015 does not have a means for declaring properties on classes. Properties are dynamically assigned, just like object literals.
12+
ES2015 不提供在类中声明属性的方法。属性是动态分配的,就像对象字面量一样。
1313

14-
In a `.js` file, the compiler infers properties from property assignments inside the class body.
15-
The type of a property is the type given in the constructor, unless it's not defined there, or the type in the constructor is undefined or null.
16-
In that case, the type is the union of the types of all the right-hand values in these assignments.
17-
Properties defined in the constructor are always assumed to exist, whereas ones defined just in methods, getters, or setters are considered optional.
14+
`.js` 文件中,编译器从类体内的属性赋值推断属性。属性的类型是构造函数中给出的类型,除非它未在构造函数中定义,或者构造函数中的类型是 undefined 或 null。在这种情况下,类型是所有右侧赋值类型的联合。构造函数中定义的属性总是被认为存在,而仅在方法、getter 或 setter 中定义的属性被认为是可选的。
1815

1916
```js twoslash
2017
// @checkJs
@@ -26,18 +23,16 @@ class C {
2623
}
2724
method() {
2825
this.constructorOnly = false;
29-
this.constructorUnknown = "plunkbat"; // ok, constructorUnknown is string | undefined
30-
this.methodOnly = "ok"; // ok, but methodOnly could also be undefined
26+
this.constructorUnknown = "plunkbat"; // ok, constructorUnknown string | undefined
27+
this.methodOnly = "ok"; // ok,但 methodOnly 也可能是 undefined
3128
}
3229
method2() {
33-
this.methodOnly = true; // also, ok, methodOnly's type is string | boolean | undefined
30+
this.methodOnly = true; // okmethodOnly 的类型是 string | boolean | undefined
3431
}
3532
}
3633
```
3734

38-
If properties are never set in the class body, they are considered unknown.
39-
If your class has properties that are only read from, add and then annotate a declaration in the constructor with JSDoc to specify the type.
40-
You don't even have to give a value if it will be initialized later:
35+
如果属性在类体中从未设置,则它们被视为未知。如果类中有仅被读取的属性,请在构造函数中添加并注释声明,指定类型使用 JSDoc。即使稍后初始化,也无需提供值:
4136

4237
```js twoslash
4338
// @checkJs
@@ -56,11 +51,9 @@ c.prop = 0; // OK
5651
c.count = "string";
5752
```
5853

59-
## Constructor functions are equivalent to classes
54+
## 构造函数等同于类
6055

61-
Before ES2015, JavaScript used constructor functions instead of classes.
62-
The compiler supports this pattern and understands constructor functions as equivalent to ES2015 classes.
63-
The property inference rules described above work exactly the same way.
56+
在 ES2015 之前,JavaScript 使用构造函数而不是类。编译器支持这种模式,并将构造函数视为等同于 ES2015 类。上述属性推断规则的工作方式完全相同。
6457

6558
```js twoslash
6659
// @checkJs
@@ -71,40 +64,36 @@ function C() {
7164
}
7265
C.prototype.method = function () {
7366
this.constructorOnly = false;
74-
this.constructorUnknown = "plunkbat"; // OK, the type is string | undefined
67+
this.constructorUnknown = "plunkbat"; // OK,类型是 string | undefined
7568
};
7669
```
7770

78-
## CommonJS modules are supported
71+
## 支持 CommonJS 模块
7972

80-
In a `.js` file, TypeScript understands the CommonJS module format.
81-
Assignments to `exports` and `module.exports` are recognized as export declarations.
82-
Similarly, `require` function calls are recognized as module imports. For example:
73+
`.js` 文件中,TypeScript 理解 CommonJS 模块格式。对 `exports``module.exports` 的赋值被识别为导出声明。类似地,`require` 函数调用被识别为模块导入。例如:
8374

8475
```js
85-
// same as `import module "fs"`
76+
// 同于 `import module "fs"`
8677
const fs = require("fs");
8778

88-
// same as `export function readFile`
79+
// 同于 `export function readFile`
8980
module.exports.readFile = function (f) {
9081
return fs.readFileSync(f);
9182
};
9283
```
9384

94-
The module support in JavaScript is much more syntactically forgiving than TypeScript's module support.
95-
Most combinations of assignments and declarations are supported.
85+
JavaScript 中的模块支持在语法上比 TypeScript 的模块支持更宽松。大多数赋值和声明的组合都是支持的。
9686

97-
## Classes, functions, and object literals are namespaces
87+
## 类、函数和对象字面量是命名空间
9888

99-
Classes are namespaces in `.js` files.
100-
This can be used to nest classes, for example:
89+
`.js` 文件中,类可以作为命名空间。这可以用于嵌套类,例如:
10190

10291
```js twoslash
10392
class C {}
10493
C.D = class {};
10594
```
10695

107-
And, for pre-ES2015 code, it can be used to simulate static methods:
96+
对于 ES2015 之前的代码,它可以用来模拟静态方法:
10897

10998
```js twoslash
11099
function Outer() {
@@ -118,7 +107,7 @@ Outer.Inner = function () {
118107
Outer.Inner();
119108
```
120109

121-
It can also be used to create simple namespaces:
110+
它还可以用来创建简单的命名空间:
122111

123112
```js twoslash
124113
var ns = {};
@@ -128,39 +117,36 @@ ns.func = function () {};
128117
ns;
129118
```
130119

131-
Other variants are allowed as well:
120+
其他变体也是允许的:
132121

133122
```js twoslash
134-
// IIFE
123+
// 自执行函数
135124
var ns = (function (n) {
136125
return n || {};
137126
})();
138127
ns.CONST = 1;
139128

140-
// defaulting to global
129+
// 默认为全局
141130
var assign =
142131
assign ||
143132
function () {
144-
// code goes here
133+
// 代码在这里
145134
};
146135
assign.extra = 1;
147136
```
148137

149-
## Object literals are open-ended
138+
## 对象字面量是开放式的
150139

151-
In a `.ts` file, an object literal that initializes a variable declaration gives its type to the declaration.
152-
No new members can be added that were not specified in the original literal.
153-
This rule is relaxed in a `.js` file; object literals have an open-ended type (an index signature) that allows adding and looking up properties that were not defined originally.
154-
For instance:
140+
`.ts` 文件中,初始化变量声明的对象字面量会将其类型赋给该声明。不能添加在原始字面量中未指定的新成员。在 `.js` 文件中,这条规则放宽了;对象字面量具有开放式类型(索引签名),允许添加和查找原本未定义的属性。例如:
155141

156142
```js twoslash
157143
var obj = { a: 1 };
158-
obj.b = 2; // Allowed
144+
obj.b = 2; // 允许
159145
```
160146

161-
Object literals behave as if they have an index signature `[x:string]: any` that allows them to be treated as open maps instead of closed objects.
147+
对象字面量的行为就像拥有一个索引签名 `[x:string]: any`,这使得它们可以被视为开放映射,而不是封闭对象。
162148

163-
Like other special JS checking behaviors, this behavior can be changed by specifying a JSDoc type for the variable. For example:
149+
与其他特殊的 JS 检查行为一样,通过为变量指定 JSDoc 类型,可以改变这种行为。例如:
164150

165151
```js twoslash
166152
// @checkJs
@@ -170,11 +156,9 @@ var obj = { a: 1 };
170156
obj.b = 2;
171157
```
172158

173-
## null, undefined, and empty array initializers are of type any or any[]
159+
## nullundefined 和空数组初始化器的类型为 any any[]
174160

175-
Any variable, parameter or property that is initialized with null or undefined will have type any, even if strict null checks is turned on.
176-
Any variable, parameter or property that is initialized with [] will have type any[], even if strict null checks is turned on.
177-
The only exception is for properties that have multiple initializers as described above.
161+
任何用 null 或 undefined 初始化的变量、参数或属性的类型将为 any,即使开启了严格的 null 检查。任何用 [] 初始化的变量、参数或属性的类型将为 any[],即使开启了严格的 null 检查。唯一的例外是具有多个初始化器的属性,如上所述。
178162

179163
```js twoslash
180164
function Foo(i = null) {
@@ -189,14 +173,13 @@ foo.l.push(foo.i);
189173
foo.l.push("end");
190174
```
191175

192-
## Function parameters are optional by default
176+
## 函数参数默认是可选的
193177

194-
Since there is no way to specify optionality on parameters in pre-ES2015 JavaScript, all function parameters in `.js` file are considered optional.
195-
Calls with fewer arguments than the declared number of parameters are allowed.
178+
由于在 ES2015 之前的 JavaScript 中无法指定参数的可选性,因此在 `.js` 文件中的所有函数参数都被视为可选。调用时,如果提供的参数少于声明的参数数量是允许的。
196179

197-
It is important to note that it is an error to call a function with too many arguments.
180+
需要注意的是,调用函数时提供过多参数会导致错误。
198181

199-
For instance:
182+
例如:
200183

201184
```js twoslash
202185
// @checkJs
@@ -206,17 +189,16 @@ function bar(a, b) {
206189
console.log(a + " " + b);
207190
}
208191

209-
bar(1); // OK, second argument considered optional
192+
bar(1); // OK,第二个参数被视为可选
210193
bar(1, 2);
211-
bar(1, 2, 3); // Error, too many arguments
194+
bar(1, 2, 3); // 错误,参数过多
212195
```
213196

214-
JSDoc annotated functions are excluded from this rule.
215-
Use JSDoc optional parameter syntax (`[` `]`) to express optionality. e.g.:
197+
带有 JSDoc 注释的函数不受此规则的限制。使用 JSDoc 可选参数语法(`[` `]`)来表示可选性。例如:
216198

217199
```js twoslash
218200
/**
219-
* @param {string} [somebody] - Somebody's name.
201+
* @param {string} [somebody] - 某人的名字。
220202
*/
221203
function sayHello(somebody) {
222204
if (!somebody) {
@@ -228,9 +210,9 @@ function sayHello(somebody) {
228210
sayHello();
229211
```
230212

231-
## Var-args parameter declaration inferred from use of `arguments`
213+
## `arguments` 的使用推断可变参数声明
232214

233-
A function whose body has a reference to the `arguments` reference is implicitly considered to have a var-arg parameter (i.e. `(...arg: any[]) => any`). Use JSDoc var-arg syntax to specify the type of the arguments.
215+
函数体中引用 `arguments` 的函数隐式地被认为具有可变参数(即 `(...arg: any[]) => any`)。使用 JSDoc 可变参数语法来指定参数的类型。
234216

235217
```js twoslash
236218
/** @param {...number} args */
@@ -243,26 +225,25 @@ function sum(/* numbers */) {
243225
}
244226
```
245227

246-
## Unspecified type parameters default to `any`
228+
## 未指定的类型参数默认值为 `any`
247229

248-
Since there is no natural syntax for specifying generic type parameters in JavaScript, an unspecified type parameter defaults to `any`.
230+
由于在 JavaScript 中没有自然的语法来指定泛型类型参数,未指定的类型参数默认值为 `any`
249231

250-
### In extends clause
232+
### extends 子句中
251233

252-
For instance, `React.Component` is defined to have two type parameters, `Props` and `State`.
253-
In a `.js` file, there is no legal way to specify these in the extends clause. By default the type arguments will be `any`:
234+
例如,`React.Component` 被定义为具有两个类型参数 `Props``State`。在 `.js` 文件中,没有合法的方法在 extends 子句中指定这些参数。默认情况下,类型参数将为 `any`
254235

255236
```js
256237
import { Component } from "react";
257238

258239
class MyComponent extends Component {
259240
render() {
260-
this.props.b; // Allowed, since this.props is of type any
241+
this.props.b; // 允许,因为 this.props 的类型为 any
261242
}
262243
}
263244
```
264245

265-
Use JSDoc `@augments` to specify the types explicitly. for instance:
246+
使用 JSDoc `@augments` 来显式指定类型。例如:
266247

267248
```js
268249
import { Component } from "react";
@@ -272,32 +253,32 @@ import { Component } from "react";
272253
*/
273254
class MyComponent extends Component {
274255
render() {
275-
this.props.b; // Error: b does not exist on {a:number}
256+
this.props.b; // 错误:b 在 {a:number} 上不存在
276257
}
277258
}
278259
```
279260

280-
### In JSDoc references
261+
### JSDoc 引用中
281262

282-
An unspecified type argument in JSDoc defaults to any:
263+
JSDoc 中未指定的类型参数默认值为 any
283264

284265
```js twoslash
285266
/** @type{Array} */
286267
var x = [];
287268

288269
x.push(1); // OK
289-
x.push("string"); // OK, x is of type Array<any>
270+
x.push("string"); // OK,x 的类型为 Array<any>
290271

291272
/** @type{Array.<number>} */
292273
var y = [];
293274

294275
y.push(1); // OK
295-
y.push("string"); // Error, string is not assignable to number
276+
y.push("string"); // 错误,string 不能赋值给 number
296277
```
297278

298-
### In function calls
279+
### 在函数调用中
299280

300-
A call to a generic function uses the arguments to infer the type parameters. Sometimes this process fails to infer any types, mainly because of lack of inference sources; in these cases, the type parameters will default to `any`. For example:
281+
调用一个泛型函数时,会使用参数推断类型参数。有时这个过程无法推断出任何类型,主要是由于缺乏推断来源;在这些情况下,类型参数将默认为 any。例如:
301282

302283
```js
303284
var p = new Promise((resolve, reject) => {
@@ -307,4 +288,4 @@ var p = new Promise((resolve, reject) => {
307288
p; // Promise<any>;
308289
```
309290

310-
To learn all of the features available in JSDoc, see [the reference](/zh/docs/handbook/jsdoc-supported-types.html).
291+
要了解 JSDoc 中可用的所有功能,请参见 [参考文档](/docs/handbook/jsdoc-supported-types.html)

0 commit comments

Comments
 (0)