Function declaration
Function declaration là cú pháp để định nghĩa function trong JavaScript.
Cú pháp function declaration
Function declaration trong JavaScript sử dụng cú pháp function.
jsfunctionhello () {return "hello";}
jsfunctionhello () {return "hello";}
Type annotation cho function declaration
Trong TypeScript, bạn có thể viết type annotation cho tham số và giá trị trả về của function declaration.
tsfunctionincrement (num : number): number {returnnum + 1;}
tsfunctionincrement (num : number): number {returnnum + 1;}
Khi bỏ qua type annotation cho tham số, compiler sẽ ngầm hiểu nó là kiểu any.
tsfunctionincrement (num ): number {returnnum + 1;}
tsfunctionincrement (num ): number {returnnum + 1;}
Bằng cách đặt compiler option noImplicitAny thành true, bạn có thể bắt buộc type annotation cho tham số.
tsfunctionParameter 'num' implicitly has an 'any' type.7006Parameter 'num' implicitly has an 'any' type.increment (): number { num returnnum + 1;}
tsfunctionParameter 'num' implicitly has an 'any' type.7006Parameter 'num' implicitly has an 'any' type.increment (): number { num returnnum + 1;}
📄️ noImplicitAny
Cấm any type ngầm định
Khi bỏ qua type annotation cho giá trị trả về, compiler sẽ suy luận kiểu từ code.
tsfunctionincrement (num : number) {returnnum + 1;}constvalue =increment (1);
tsfunctionincrement (num : number) {returnnum + 1;}constvalue =increment (1);
Khi có nhiều return và trả về các kiểu khác nhau, kiểu được suy luận sẽ là union type.
tsfunctiongetFirst (items : number[]) {if (typeofitems [0] === "number") {returnitems [0];}return null;}getFirst ([1, 2, 3]);
tsfunctiongetFirst (items : number[]) {if (typeofitems [0] === "number") {returnitems [0];}return null;}getFirst ([1, 2, 3]);