Skip to content

Commit 0a916f7

Browse files
committed
在实例字段上检查 super 属性访问
1 parent b993add commit 0a916f7

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

zh/release-notes/typescript-5.3.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,3 +224,77 @@ function f(value: unknown) {
224224
这意味着我们可以访问属性 `x``y`,但无法访问 `distanceFromOrigin` 方法。
225225

226226
更多详情请参考[PR](https://github.com/microsoft/TypeScript/pull/55052)
227+
228+
## 在实例字段上检查 `super` 属性访问
229+
230+
在 JavaScript 中,能够使用 `super` 关键字来访问基类中的声明。
231+
232+
```ts
233+
class Base {
234+
someMethod() {
235+
console.log("Base method called!");
236+
}
237+
}
238+
239+
class Derived extends Base {
240+
someMethod() {
241+
console.log("Derived method called!");
242+
super.someMethod();
243+
}
244+
}
245+
246+
new Derived().someMethod();
247+
// Prints:
248+
// Derived method called!
249+
// Base method called!
250+
```
251+
252+
这与 `this.someMethod()` 是不同的,因为它可能调用的是重写的方法。
253+
这是一个微妙的区别,而且通常情况下,如果一个声明从未被覆盖,这两者可以互换,使得区别更加微妙。
254+
255+
```ts
256+
class Base {
257+
someMethod() {
258+
console.log("someMethod called!");
259+
}
260+
}
261+
262+
class Derived extends Base {
263+
someOtherMethod() {
264+
// These act identically.
265+
this.someMethod();
266+
super.someMethod();
267+
}
268+
}
269+
270+
new Derived().someOtherMethod();
271+
// Prints:
272+
// someMethod called!
273+
// someMethod called!
274+
```
275+
276+
将它们互换使用的问题在于,`super` 关键字仅适用于在原型上声明的成员,而不适用于实例属性。
277+
这意味着,如果您编写了 `super.someMethod()`,但 `someMethod` 被定义为一个字段,那么您将会得到一个运行时错误!
278+
279+
```ts
280+
class Base {
281+
someMethod = () => {
282+
console.log("someMethod called!");
283+
}
284+
}
285+
286+
class Derived extends Base {
287+
someOtherMethod() {
288+
super.someMethod();
289+
}
290+
}
291+
292+
new Derived().someOtherMethod();
293+
//
294+
// Doesn't work because 'super.someMethod' is 'undefined'.
295+
```
296+
297+
TypeScript 5.3 现在更仔细地检查 `super` 属性访问/方法调用,以确定它们是否对应于类字段。
298+
如果是这样,我们现在将会得到一个类型检查错误。
299+
300+
[这个检查](https://github.com/microsoft/TypeScript/pull/54056)是由 Jack Works 开发!

0 commit comments

Comments
 (0)