Nhảy tới nội dung

strictBindCallApply

strictBindCallApply là compiler option làm nghiêm ngặt type check của bind, call, apply.

  • Mặc định: true nế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 strictBindCallApplyfalse (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 string
function fn(x: string) {}
 
// Tham số truyền vào là kiểu number nhưng không cảnh báo
fn.call(undefined, 122);
ts
// Function có tham số kiểu string
function fn(x: string) {}
 
// Tham số truyền vào là kiểu number nhưng không cảnh báo
fn.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.

ts
function fn(): string {
return "str";
}
const x = fn.call(undefined);
const x: any
ts
function fn(): string {
return "str";
}
const x = fn.call(undefined);
const x: any

Khi strictBindCallApplyfalse, có nguy cơ xảy ra lỗi runtime.

ts
function fn(x: string) {
x.toUpperCase();
}
const x = fn.call(undefined, 123);
TypeError: x.toUpperCase is not a function
ts
function fn(x: string) {
x.toUpperCase();
}
const x = fn.call(undefined, 123);
TypeError: x.toUpperCase is not a function

Type check của bind, call, apply

Đặt strictBindCallApply thành true để type check bind, call, apply.

ts
function fn(x: string) {}
fn.call(undefined, 123);
Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.
ts
function fn(x: string) {}
fn.call(undefined, 123);
Argument of type 'number' is not assignable to parameter of type 'string'.2345Argument of type 'number' is not assignable to parameter of type 'string'.

Thêm nữa, type của return value sẽ là return value type của function được gọi.

ts
function fn(): string {
return "str";
}
const x = fn.call(undefined);
const x: string
ts
function fn(): string {
return "str";
}
const x = fn.call(undefined);
const x: string

Nhờ return value có type nên còn có lợi ích là có autocomplete.

ts
function fn(): string {
return "str";
}
const str = fn.call(undefined);
str.toU;
       
ts
function fn(): string {
return "str";
}
const str = 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』

Đăng nội dung này lên X

Thông tin liên quan

📄️ strict

Bật hàng loạt các option thuộc nhóm strict