TypeScript override & overload All In One
TypeScript override & overload All In One
TypeScript override
class SomeComponent {
show() {
// ...
}
hide() {
// ...
}
}
// ❌ 子类继承父类,名称重复导致意外覆盖了父类的同名函数
class SpecializedComponent extends SomeComponent {
show() {
// ...
}
hide() {
// ...
}
}
class SomeComponent {
- show() {
- // ...
- }
- hide() {
- // ...
- }
+ setVisible(value: boolean) {
+ // ...
+ }
}
// 当父类的方法实现发生变化时,子类是不会提示错误信息
class SpecializedComponent extends SomeComponent {
show() {
// ...
}
hide() {
// ...
}
}
solution, 强制显式的使用
override
关键字
// override 防止误覆盖父类中的同名方法 ✅
class SpecializedComponent extends SomeComponent {
override show() {
// ...
}
override hide() {
// ...
}
}
class SomeComponent {
setVisible(value: boolean) {
// ...
}
}
// 覆盖父类没有的方法,会看到错误提示信息 ✅
class SpecializedComponent extends SomeComponent {
override show() {
// This member cannot have an 'override' modifier because it is not declared in the base class 'SomeComponent'.
}
}
TypeScript overloads
// bad 👎
function len(s: string): number;
function len(arr: any[]): number;
function len(x: any) {
return x.length;
}
function len(s: string): number;
function len(arr: any[]): number;
function len(x: any) {
return x.length;
}
len(""); // OK
len([0]); // OK
len(Math.random() > 0.5 ? "hello" : [0]);
// ❌
/*
No overload matches this call.
Overload 1 of 2, '(s: string): number', gave the following error.
Argument of type 'number[] | "hello"' is not assignable to parameter of type 'string'.
Type 'number[]' is not assignable to type 'string'.
Overload 2 of 2, '(arr: any[]): number', gave the following error.
Argument of type 'number[] | "hello"' is not assignable to parameter of type 'any[]'.
Type 'string' is not assignable to type 'any[]'.(2769)
input.tsx(3, 10): The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible.
*/
// good 👍
function len(x: any[] | string) {
return x.length;
}
https://www.typescriptlang.org/docs/handbook/functions.html#overloads
https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads
https://www.typescriptlang.org/tsconfig/#noImplicitOverride
js overload function & js override function
- 函数重载 overload
函数名相同,函数的参数不同(参数个数/参数类型/参数个数 & 参数类型)
- 函数覆写(覆盖) override / rewriter
函数名相同,函数的参数相同(参数个数 & 参数类型)
https://www.cnblogs.com/xgqfrms/p/14434635.html
refs
https://github.com/microsoft/TypeScript/issues/31788
https://stackoverflow.com/questions/40973074/difference-between-interfaces-and-classes-in-typescript
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16087727.html
未经授权禁止转载,违者必究!