strictBindCallApply
strictBindCallApply là compiler option làm nghiêm ngặt type check của bind, call, apply.
- Mặc định:
truenếu strict được bật, ngược lại làfalse - Phiên bản thêm vào: 3.2
- TypeScript khuyến nghị nên bật
bind, call, apply không được type check
Khi strictBindCallApply là false (mặc định của TypeScript), không check type của tham số của built-in function bind, call, apply.
ts// Function có tham số kiểu stringfunctionfn (x : string) {}// Tham số truyền vào là kiểu number nhưng không cảnh báofn .call (undefined , 122);
ts// Function có tham số kiểu stringfunctionfn (x : string) {}// Tham số truyền vào là kiểu number nhưng không cảnh báofn .call (undefined , 122);
Type annotation của return value của function được gọi bằng bind, call, apply bị bỏ qua, type của return value sẽ là any.
tsfunctionfn (): string {return "str";}constx =fn .call (undefined );
tsfunctionfn (): string {return "str";}constx =fn .call (undefined );
Khi strictBindCallApply là false, có nguy cơ xảy ra lỗi runtime.
tsfunctionfn (x : string) {x .toUpperCase ();}constx =fn .call (undefined , 123);
tsfunctionfn (x : string) {x .toUpperCase ();}constx =fn .call (undefined , 123);
Type check của bind, call, apply
Đặt strictBindCallApply thành true để type check bind, call, apply.
tsfunctionfn (x : string) {}Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.fn .call (undefined ,123 );
tsfunctionfn (x : string) {}Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.fn .call (undefined ,123 );
Thêm nữa, type của return value sẽ là return value type của function được gọi.
tsfunctionfn (): string {return "str";}constx =fn .call (undefined );
tsfunctionfn (): string {return "str";}constx =fn .call (undefined );
Nhờ return value có type nên còn có lợi ích là có autocomplete.
tsfunctionfn (): string {return "str";}conststr =fn .call (undefined );str .toU ;
tsfunctionfn (): string {return "str";}conststr =fn .call (undefined );str .toU ;
Khuyến nghị nên bật strictBindCallApply.
Chia sẻ kiến thức
strictBindCallApply của TypeScript là compiler option làm nghiêm ngặt type check của bind, call, apply
【Khi false】
❌Không check type của tham số
⚠️Return value trở thành any
【Khi true】
✅Check type của tham số
💚Return value có type
👍Khuyến nghị nên bật
Từ 『Survival TypeScript』
Thông tin liên quan
📄️ strict
Bật hàng loạt các option thuộc nhóm strict