TS03 Exercises
Note: You do not need to memorize every compiler option. But experiment with those and try to understand what they are for.
Practical Exercises
- Write a simple TypeScript program with a few type annotations. Compile it using the TypeScript compiler (
tsc) from the command line without atsconfig.jsonfile. Observe the generated JavaScript code to understand how TypeScript erases types.
// simple.ts
function greet(name: string): void {
console.log(`Hello, ${name}!`);
}
greet("Alice");Compile using: tsc simple.ts
Observe: TypeScript types are removed in the JavaScript output.
- Write a TypeScript program using ES6 features like arrow functions and
const/let. Use the tsc command to compile the TypeScript file to ES5 JavaScript. Examine the output to see howtscdownlevels ES6 code to ES5.
// es6features.ts
const greet = (name: string): void => {
console.log(`Hello, ${name}!`);
};
greet("Alice");Compile using: tsc es6features.ts --target ES5
Observe: Arrow functions and const/let are converted to ES5 syntax in the JavaScript output.
- Create a tsconfig.json file with the strict flag set to true. Write TypeScript code that would cause compilation errors under strict mode but would pass without it.
// tsconfig.json
{
"compilerOptions": {
"strict": true
}
}// strictModeExample.ts
let untyped; // Error in strict mode: Variable 'untyped' implicitly has an 'any' type.
untyped = "This is a string";
console.log(untyped);- Write a
tsconfig.jsonfile and experiment with different compilerOptions. Specifically, change the target, lib, module, moduleResolution, and esModuleInterop settings, and observe how these changes affect the compiled JavaScript output.
// tsconfig.json
{
"compilerOptions": {
"target": "es6",
"lib": ["dom", "es2015"],
"module": "commonjs",
"moduleResolution": "node",
"esModuleInterop": true
}
}Observe: Changes in the compiled JavaScript output based on these settings.
- Create a base tsconfig.json file, and then extend it in a specific tsconfig file for a particular directory in your project.
// tsconfig.base.json
{
"compilerOptions": {
"strict": true,
"target": "es6"
}
}// specific/tsconfig.json
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist"
}
}Theoretical Exercises
- Explain what happens when TypeScript code is compiled. What does the term "erasing types" mean in the context of TypeScript?
When TypeScript code is compiled, it is transformed into JavaScript. "Erasing types" means that TypeScript's type annotations are removed in the compiled output, as JavaScript doesn't have these types. This process ensures compatibility with the JavaScript runtime environment.
- What is downleveling in TypeScript, and why is it important for web development?
Downleveling in TypeScript refers to the process of converting modern TypeScript (or JavaScript) code into an older version of JavaScript for compatibility with older browsers or environments. It's crucial for web development to ensure that web applications work across all browsers, including those that do not support the latest JavaScript features.
- Describe the purpose of enabling strict mode in TypeScript. What are some of the errors that strict mode can help prevent?
Enabling strict mode in TypeScript enforces a stricter type-checking, which can help catch potential issues early in development. It helps prevent errors such as implicit any types, null/undefined errors, unused parameters/variables, and ensures proper handling of 'this' keyword context.
- What is the role of the tsconfig.json file in a TypeScript project? How does it affect the compilation process?
The tsconfig.json file in a TypeScript project specifies the root files and the compiler options required for the project. It affects the compilation process by determining how the TypeScript compiler will transpile the code, including what JavaScript version to output, which files to include or exclude, and various other settings that impact type-checking and code generation.
- Explain the purpose of the include and exclude options in tsconfig.json. How do they differ from each other?
The include and exclude options in tsconfig.json specify which files should be included in or excluded from the compilation process. 'include' defines the files to be compiled, whereas 'exclude' specifies files that should be ignored. Both options help in managing the scope of the compilation in a TypeScript project.
- Describe the effect of the following compiler options and why they might be used in a project:
- target
- lib
- strict
- module
- moduleResolution
- esModuleInterop
- jsx
- skipLibCheck
target: Specifies the ECMAScript target version for the output JavaScript code.lib: Defines the library files that will be included in the compilation.strict: Enables all strict type-checking options, improving code safety and maintainability.module: Specifies the module code generation method (e.g., CommonJS, ES6).moduleResolution: Determines how modules get resolved.esModuleInterop: Enables compatibility with Babel-style module imports.jsx: Specifies JSX code handling, important for React or similar frameworks.skipLibCheck: Skips type checking of declaration files, improving compile times but reducing type safety.
- What are TSConfig bases, and how can they be utilized in large projects with multiple types of environments (like development and production)?
TSConfig bases refer to base configuration files that can be extended by other tsconfig files. They are useful in large projects to maintain consistent compiler settings across multiple environments (like development and production), reducing duplication and making configuration management more efficient.
- Explain the esModuleInterop flag in TypeScript's compiler options. What problem does it solve in terms of module interoperability?
The esModuleInterop flag in TypeScript's compiler options enables a more compliant handling of ES6 modules. It solves the problem of interoperability between CommonJS and ES6 modules, allowing the use of default import syntax with modules that do not have a default export.
- How does TypeScript handle JSX? What are the implications of different jsx settings in tsconfig.json for a project using JSX syntax?
TypeScript handles JSX by providing various modes in the jsx setting, like react, preserve, and react-native. These settings determine how JSX is compiled into JavaScript. For instance, react mode compiles JSX into React.createElement calls, while preserve keeps the JSX intact in the output, typically to be handled by a later stage in the build process like Babel.
- Discuss the impact and use cases of advanced TypeScript compiler options such as noImplicitAny, noUnusedLocals, and noUnusedParameters.
noImplicitAny: Prevents variables from having an implicit 'any' type, enforcing more explicit and safer type annotations.noUnusedLocals: Detects and reports unused local variables, helping to keep the codebase cleaner and more readable.noUnusedParameters: Similar tonoUnusedLocals, but for function parameters, ensuring that all declared parameters are used. These options are particularly useful in large codebases to maintain code quality and prevent potential bugs.