All Tracks/lecture introduction to typescript/
Đang tải...
Hướng dẫn thử thách
1 / 4

What Is TypeScript, and Why Is It Used in the Industry?

JavaScript is considered a dynamically-typed language. This means that variables can receive any values at run time - declaring a variable as a number does not prevent you from assigning it a string value later, and function parameters can be passed any value. The challenge of a dynamically-typed language is that the lack of type safety can introduce errors if you are not careful. TypeScript extends the JavaScript language to include static typing, which helps catch those errors before you even deploy your code. But how does it work? Consider this JavaScript function: ```js const getRandomValue = (array) => { return array[Math.floor(Math.random() * array.length)]; } ``` Our `getRandomValue` function takes an array and returns a random value from that array. But because JavaScript does not validate types, there is nothing preventing you from calling the function with a number: ```js console.log(getRandomValue(10)); ``` The console output for the current example will return `undefined` because it was expecting an array instead of a number. But with TypeScript you can define a type for the array parameter: ```js const getRandomValue = (array: string[]) => { return array[Math.floor(Math.random() * array.length)]; } ``` This type definition tells TypeScript that the array argument must be an array of strings. Then when you call `getRandomValue` and pass it a number, you get a different type of error called a compiler error. Most JavaScript runtime environments, such as a browser or Node.js, cannot run TypeScript natively. Instead, you first need to compile, or translate, TypeScript code into regular JavaScript. You can do that with the built-in compiler that comes with the TypeScript language. When you run the compiler, TypeScript will evaluate your code and throw an error for any issues where the types don't match - such as passing a number into a function that expects an array. You'll learn more about how these types work in the next few lessons. But it's this extra safety that makes TypeScript an appealing language for many developers and organizations.
Vượt qua bài kiểm tra hiện tại để mở khóa bài tiếp theo.
main.ts
UTF-8 • Tab Size: 2Kiểm tra bài:⌘↵
Test Output
Thử thách này không có bài test tự động. Hãy quan sát kết quả trực tiếp ở khung Preview.