diff --git a/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/BasicTypes.jsx b/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/BasicTypes.jsx new file mode 100644 index 0000000..c1d1fe2 --- /dev/null +++ b/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/BasicTypes.jsx @@ -0,0 +1,423 @@ +import React from 'react'; +import CodeBlock from '../../../components/CodeBlock'; + +const BasicTypes = () => { + return ( +
+
+

+ Basic Types +

+ +
+

+ Basic types are the fundamental data types that TypeScript supports. + They provide type safety for the most common JavaScript values and operations. +

+
+ +

+ Primitive Types +

+ +

+ These are the basic building blocks of TypeScript's type system, corresponding to JavaScript's primitive values. +

+ +

+ String Type +

+ + + +

+ Number Type +

+ + + +

+ Boolean Type +

+ + 5);`} + /> + +

+ Special Types +

+ +

+ Null and Undefined +

+ + + +

+ Void Type +

+ + { + console.log("This function returns nothing"); +};`} + /> + +

+ Any Type +

+ + + +

+ Array Types +

+ +

+ Basic Array Types +

+ + = ["red", "green", "blue"]; // Alternative syntax + +// Array of numbers +let scores: number[] = [85, 92, 78, 96]; +let temperatures: Array = [20, 25, 30, 15]; + +// Array of booleans +let flags: boolean[] = [true, false, true]; +let permissions: Array = [true, true, false];`} + /> + +

+ Mixed Array Types +

+ + = ["yes", true, "no", false]; + +// Array with any type (avoid when possible) +let anyArray: any[] = ["string", 42, true, { name: "John" }]; + +// Empty array with type annotation +let emptyStrings: string[] = []; +let emptyNumbers: number[] = [];`} + /> + +

+ Object Types +

+ +

+ Inline Object Types +

+ + + +

+ Object with Index Signatures +

+ + + +

+ Type Literals +

+ +

+ String Literals +

+ + + +

+ Numeric Literals +

+ + + +

+ Type Checking Examples +

+ +
+
+

✅ Valid Type Usage

+ +
+ +
+

❌ Type Errors

+ +
+
+ +

+ Type Guards and Checking +

+ +

+ typeof Operator +

+ + + +

+ Array Type Checking +

+ + (items: T[]): T | undefined { + return items.length > 0 ? items[0] : undefined; +} + +const numbers = [1, 2, 3]; +const firstNumber = getFirstItem(numbers); // Type: number | undefined`} + /> + +

+ Best Practices for Basic Types +

+ +
+
+

Type Safety Tips

+
    +
  • Use specific types instead of any when possible
  • +
  • Prefer unknown over any for dynamic values
  • +
  • Use union types for values that can be one of several types
  • +
  • Use literal types for fixed sets of values
  • +
  • Always type function parameters and return values
  • +
+
+ +
+

Common Patterns

+
    +
  • Use string | null for optional string values
  • +
  • Use number | undefined for optional numbers
  • +
  • Use boolean for flags and toggles
  • +
  • Use void for functions that don't return values
  • +
  • Use never for functions that never return
  • +
+
+
+ +
+

+ Remember: Basic types are the foundation of TypeScript's type system. + They provide type safety for the most common JavaScript values and help catch errors early in development. +

+
+
+
+ ); +}; + +export default BasicTypes; diff --git a/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/TypeAnnotations.jsx b/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/TypeAnnotations.jsx new file mode 100644 index 0000000..411037d --- /dev/null +++ b/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/TypeAnnotations.jsx @@ -0,0 +1,329 @@ +import React from 'react'; +import CodeBlock from '../../../components/CodeBlock'; + +const TypeAnnotations = () => { + return ( +
+
+

+ Type Annotations +

+ +
+

+ Type annotations are explicit type declarations that tell TypeScript what type a variable, + function parameter, or return value should be. They help catch errors and provide better IDE support. +

+
+ +

+ Variable Type Annotations +

+ +

+ You can add type annotations to variables using a colon followed by the type. +

+ + + +

+ When to Use Variable Annotations +

+ +
+

Use type annotations when:

+
    +
  • TypeScript can't infer the type correctly
  • +
  • You want to be explicit about the expected type
  • +
  • Working with complex types or generics
  • +
  • Documenting code for other developers
  • +
+
+ +

+ Function Type Annotations +

+ +

+ Parameter Types +

+ + { + return length * width; +}; + +// Function with optional parameters +function createUser(name: string, email: string, age?: number): object { + return { + name, + email, + age: age || 0 + }; +}`} + /> + +

+ Return Type Annotations +

+ + { + const response = await fetch(url); + return response.json(); +}`} + /> + +

+ Object Type Annotations +

+ +

+ Inline Object Types +

+ + + +

+ Array Type Annotations +

+ + = ["red", "green", "blue"];`} + /> + +

+ Advanced Type Annotations +

+ +

+ Union Types +

+ + + +

+ Function Types +

+ + number; + +// Assign a function to the variable +mathOperation = (a, b) => a + b; + +// Function that takes a function as parameter +function processNumbers( + numbers: number[], + operation: (num: number) => number +): number[] { + return numbers.map(operation); +} + +// Usage +const doubled = processNumbers([1, 2, 3], (num) => num * 2);`} + /> + +

+ Type Annotation Best Practices +

+ +
+
+

✅ Do's

+
    +
  • Use explicit types for function parameters and return values
  • +
  • Add types for complex objects and interfaces
  • +
  • Use union types when a variable can have multiple types
  • +
  • Be explicit with array types: string[] not any[]
  • +
  • Use type annotations for public API functions
  • +
+
+ +
+

❌ Don'ts

+
    +
  • Don't over-annotate simple variables where type is obvious
  • +
  • Avoid using any type unless absolutely necessary
  • +
  • Don't annotate variables when TypeScript can infer the type
  • +
  • Avoid redundant annotations: let x: number = 5 (inference is enough)
  • +
  • Don't use type assertions as a substitute for proper typing
  • +
+
+
+ +

+ Common Type Annotation Patterns +

+ +

+ Event Handlers +

+ + ): void => { + console.log('Button clicked'); +}; + +// DOM event handler +const handleInput = (event: Event): void => { + const target = event.target as HTMLInputElement; + console.log(target.value); +};`} + /> + +

+ API Responses +

+ + { + data: T; + status: number; + message: string; +} + +// Usage with type annotation +const fetchUser = async (id: string): Promise> => { + const response = await fetch(\`/api/users/\${id}\`); + return response.json(); +};`} + /> + +

+ Generic Functions +

+ + (arg: T): T { + return arg; +} + +// Usage with explicit type +const result: string = identity("hello"); +const number: number = identity(42);`} + /> + +

+ Type Annotation vs Type Inference +

+ +
+
+

Explicit Annotations

+ +

+ Use when: Type is not obvious or you want to be explicit +

+
+
+

Type Inference

+ +

+ Use when: Type is obvious from the value +

+
+
+ +
+

+ Tip: Start with type inference and add explicit annotations only when necessary. + TypeScript's inference is very good and reduces code verbosity while maintaining type safety. +

+
+
+
+ ); +}; + +export default TypeAnnotations; diff --git a/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/TypeAssertions.jsx b/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/TypeAssertions.jsx new file mode 100644 index 0000000..5014d0c --- /dev/null +++ b/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/TypeAssertions.jsx @@ -0,0 +1,425 @@ +import React from 'react'; +import CodeBlock from '../../../components/CodeBlock'; + +const TypeAssertions = () => { + return ( +
+
+

+ Type Assertions +

+ +
+

+ Type assertions tell the TypeScript compiler to treat a value as a specific type. + They don't change the runtime value - they only affect type checking at compile time. +

+
+ +

+ What are Type Assertions? +

+ +

+ Type assertions are a way to tell TypeScript "I know more about this type than you do." + They're useful when you have a value that TypeScript can't properly infer the type of, + but you know what type it should be. +

+ +
+

+ Important: Type assertions don't perform any runtime checking or conversion. + They only affect TypeScript's type checking. Use them carefully! +

+
+ +

+ Syntax for Type Assertions +

+ +

+ Angle Bracket Syntax +

+ + someValue).length; + +// With objects +let user: unknown = { name: "John", age: 25 }; +let userName: string = (<{ name: string; age: number }>user).name; + +// With arrays +let items: unknown = [1, 2, 3, 4, 5]; +let firstItem: number = (items)[0];`} + /> + +

+ As Syntax (Recommended) +

+ + + +

+ Common Use Cases +

+ +

+ DOM Element Access +

+ + document.getElementById("submit"); +button.addEventListener("click", handleClick); + +// Multiple assertions +let canvas = document.getElementById("myCanvas") as HTMLCanvasElement; +let ctx = canvas.getContext("2d") as CanvasRenderingContext2D;`} + /> + +

+ API Responses +

+ + { + const response = await fetch(\`/api/users/\${id}\`); + const data = await response.json(); + return data as User; // Assert that the response is a User +} + +// With error handling +async function fetchUserSafe(id: string): Promise { + try { + const response = await fetch(\`/api/users/\${id}\`); + const data = await response.json(); + return data as User; + } catch (error) { + console.error("Failed to fetch user:", error); + return null; + } +}`} + /> + +

+ Working with Union Types +

+ + + +

+ Type Assertion Patterns +

+ +

+ Non-null Assertion +

+ + + +

+ Const Assertions +

+ + + +

+ Type Guards vs Type Assertions +

+ +
+
+

✅ Type Guards (Safer)

+ +

+ Benefits: Runtime safety, better error handling +

+
+
+

⚠️ Type Assertions (Faster)

+ +

+ Risks: No runtime safety, potential errors +

+
+
+ +

+ Advanced Type Assertions +

+ +

+ Assertion Functions +

+ + + +

+ Complex Type Assertions +

+ + { + data: T; + status: number; + message: string; +} + +interface User { + id: number; + name: string; + email: string; +} + +// Asserting API response +async function fetchUser(id: string): Promise { + const response = await fetch(\`/api/users/\${id}\`); + const data = await response.json(); + + // Assert the entire response structure + const apiResponse = data as ApiResponse; + return apiResponse.data; +} + +// Asserting array types +function processItems(items: unknown): number[] { + return (items as number[]).filter(n => typeof n === "number"); +}`} + /> + +

+ Best Practices +

+ +
+
+

✅ Do's

+
    +
  • Use type assertions when you're certain about the type
  • +
  • Prefer type guards over assertions when possible
  • +
  • Use the 'as' syntax instead of angle brackets
  • +
  • Add runtime checks when using assertions
  • +
  • Document why you're using a type assertion
  • +
+
+ +
+

❌ Don'ts

+
    +
  • Don't use assertions to bypass type checking
  • +
  • Avoid assertions when type guards would work
  • +
  • Don't assert types without being certain
  • +
  • Avoid using 'any' with assertions
  • +
  • Don't use assertions as a quick fix for type errors
  • +
+
+
+ +

+ Common Pitfalls +

+ +

+ Runtime Errors +

+ + + +

+ Overuse of Assertions +

+ + + +
+

+ Remember: Type assertions are a powerful tool, but they should be used carefully. + They don't provide runtime safety, so always consider whether a type guard or proper type checking would be more appropriate. +

+
+
+
+ ); +}; + +export default TypeAssertions; diff --git a/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/TypeInference.jsx b/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/TypeInference.jsx new file mode 100644 index 0000000..408a8c1 --- /dev/null +++ b/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/TypeInference.jsx @@ -0,0 +1,391 @@ +import React from 'react'; +import CodeBlock from '../../../components/CodeBlock'; + +const TypeInference = () => { + return ( +
+
+

+ Type Inference +

+ +
+

+ Type inference is TypeScript's ability to automatically determine the type of a variable, + function parameter, or return value based on the context and usage. It reduces the need for explicit type annotations. +

+
+ +

+ How Type Inference Works +

+ +

+ TypeScript analyzes your code and automatically assigns types based on: +

+ + + +

+ Variable Type Inference +

+ + + +

+ Object Type Inference +

+ + + +

+ Function Type Inference +

+ +

+ Return Type Inference +

+ + a * b; // Return type: number +const formatName = (first: string, last: string) => \`\${first} \${last}\`; // Return type: string`} + /> + +

+ Parameter Type Inference +

+ + item.toString()); +} + +// Better: explicit parameter types +function processItems(items: unknown[]) { + return items.map(item => String(item)); +} + +// Contextual typing in callbacks +const numbers = [1, 2, 3, 4, 5]; +const doubled = numbers.map(n => n * 2); // TypeScript infers 'n' as 'number'`} + /> + +

+ Advanced Type Inference +

+ +

+ Best Common Type +

+ + + +

+ Contextual Typing +

+ + n % 2 === 0); // TypeScript infers 'n' as 'number' + +// Event handlers get proper typing +document.addEventListener('click', (event) => { + // TypeScript knows event is MouseEvent + console.log(event.clientX, event.clientY); +});`} + /> + +

+ Type Inference vs Explicit Types +

+ +
+
+

✅ Type Inference

+ +

+ Benefits: Less verbose, easier to maintain, type safety preserved +

+
+
+

📝 Explicit Types

+ +

+ Benefits: More explicit, better documentation, clearer intent +

+
+
+ +

+ When to Use Explicit Types +

+ +
+
+

Use Explicit Types When:

+
    +
  • TypeScript can't infer the correct type
  • +
  • You want to be more explicit about your intentions
  • +
  • Working with complex types or generics
  • +
  • Creating public APIs or libraries
  • +
  • Type inference results in a broader type than you want
  • +
+
+ +
+

Let TypeScript Infer When:

+
    +
  • The type is obvious from the context
  • +
  • You want to keep code concise
  • +
  • Type inference gives you the exact type you want
  • +
  • Working with simple, straightforward code
  • +
  • Type inference provides better type safety
  • +
+
+
+ +

+ Type Inference Examples +

+ +

+ Array Inference +

+ + n * 2); // Type: number[] +let uppercased = strings.map(s => s.toUpperCase()); // Type: string[]`} + /> + +

+ Object Inference +

+ + + +

+ Function Inference +

+ + user.name); // Type: string[] +const adults = users.filter(user => user.age >= 18); // Type: { name: string; age: number }[]`} + /> + +

+ Type Inference Best Practices +

+ +
+
+

✅ Do's

+
    +
  • Let TypeScript infer simple types when obvious
  • +
  • Use explicit types for function parameters and return values
  • +
  • Add explicit types when inference is too broad
  • +
  • Use type assertions when you know more than TypeScript
  • +
  • Trust TypeScript's inference for most cases
  • +
+
+ +
+

❌ Don'ts

+
    +
  • Don't over-annotate obvious types
  • +
  • Avoid using any to bypass inference
  • +
  • Don't ignore TypeScript's inference warnings
  • +
  • Avoid type assertions unless necessary
  • +
  • Don't fight TypeScript's inference unnecessarily
  • +
+
+
+ +

+ Debugging Type Inference +

+ +

+ Using Type Queries +

+ + + +

+ Type Inference Debugging +

+ + 0.5 ? "hello" : 42; // Type: string | number +// If you want it to be more specific: +let value: string | number = Math.random() > 0.5 ? "hello" : 42;`} + /> + +
+

+ Tip: Type inference is one of TypeScript's most powerful features. + It provides type safety with minimal code, but don't hesitate to add explicit types when they make your code clearer or more maintainable. +

+
+
+
+ ); +}; + +export default TypeInference; diff --git a/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/WhatIsTypeScript.jsx b/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/WhatIsTypeScript.jsx new file mode 100644 index 0000000..116856e --- /dev/null +++ b/client/src/pages/Notes/TypeScriptEssentials/TsTopics/TsBasics/WhatIsTypeScript.jsx @@ -0,0 +1,285 @@ +import React from 'react'; +import CodeBlock from '../../../components/CodeBlock'; + +const WhatIsTypeScript = () => { + return ( +
+
+

+ What is TypeScript? +

+ +
+

+ TypeScript is a programming language that extends JavaScript by adding static type definitions. + It's designed for the development of large applications and transcompiles to JavaScript. +

+
+ +

+ Understanding TypeScript +

+ +

+ TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale. + It's developed and maintained by Microsoft and is open source. +

+ +

+ Core Concepts +

+ +
+
+

Static Typing

+

+ Types are checked at compile time, not runtime. This catches errors before your code runs. +

+
+
+

JavaScript Superset

+

+ All valid JavaScript code is also valid TypeScript code. +

+
+
+

Compile Time

+

+ TypeScript compiles to JavaScript, which runs in any JavaScript environment. +

+
+
+

Optional Types

+

+ You can add types gradually to existing JavaScript projects. +

+
+
+ +

+ TypeScript vs JavaScript +

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AspectJavaScriptTypeScript
Type SystemDynamicStatic
Error DetectionRuntimeCompile Time
IDE SupportBasicAdvanced
RefactoringManualAutomated
Learning CurveGentleModerate
+
+ +

+ Why Use TypeScript? +

+ +

+ Early Error Detection +

+ +
+
+

JavaScript (Runtime Error)

+ +
+
+

TypeScript (Compile Error)

+ +
+
+ +

+ Better IDE Support +

+ +
+

TypeScript provides:

+
    +
  • IntelliSense: Smart autocomplete based on types
  • +
  • Error Highlighting: Real-time error detection
  • +
  • Refactoring: Safe renaming and restructuring
  • +
  • Navigation: Go to definition, find references
  • +
  • Documentation: Hover information and parameter hints
  • +
+
+ +

+ Self-Documenting Code +

+ + + +

+ TypeScript Features +

+ +
+
+

Type System

+
    +
  • Basic types (string, number, boolean, etc.)
  • +
  • Array and object types
  • +
  • Union and intersection types
  • +
  • Generic types for reusable code
  • +
  • Utility types for type manipulation
  • +
+
+ +
+

Advanced Features

+
    +
  • Interfaces and type aliases
  • +
  • Classes with access modifiers
  • +
  • Enums for named constants
  • +
  • Decorators for metadata
  • +
  • Modules and namespaces
  • +
+
+ +
+

Modern JavaScript

+
    +
  • ES6+ features with type safety
  • +
  • Async/await with proper typing
  • +
  • Destructuring with type annotations
  • +
  • Template literals with type checking
  • +
  • Arrow functions with return types
  • +
+
+
+ +

+ When to Use TypeScript +

+ +
+
+

✅ Good for:

+
    +
  • Large applications with multiple developers
  • +
  • Long-term projects requiring maintenance
  • +
  • APIs and libraries used by other developers
  • +
  • Projects where type safety is critical
  • +
  • Teams transitioning from statically typed languages
  • +
+
+
+

⚠️ Consider alternatives for:

+
    +
  • Quick prototypes or small scripts
  • +
  • Projects with very tight deadlines
  • +
  • Teams completely new to JavaScript
  • +
  • Legacy codebases with complex build processes
  • +
+
+
+ +

+ TypeScript Compilation +

+ +

+ TypeScript code is compiled to JavaScript. The TypeScript compiler (tsc) performs type checking + and then generates JavaScript code that can run in any JavaScript environment. +

+ + + +
+

Key Points:

+
    +
  • Type annotations are removed during compilation
  • +
  • Only valid JavaScript is generated
  • +
  • Type checking happens before compilation
  • +
  • Source maps can be generated for debugging
  • +
  • Declaration files (.d.ts) can be generated for type information
  • +
+
+ +
+

+ Remember: TypeScript is a tool that helps you write better JavaScript. + It doesn't replace JavaScript - it enhances it with type safety and better developer experience. +

+
+
+
+ ); +}; + +export default WhatIsTypeScript; diff --git a/client/src/pages/Notes/TypeScriptEssentials/TypeScriptEssentials.jsx b/client/src/pages/Notes/TypeScriptEssentials/TypeScriptEssentials.jsx index 238215e..acb40b7 100644 --- a/client/src/pages/Notes/TypeScriptEssentials/TypeScriptEssentials.jsx +++ b/client/src/pages/Notes/TypeScriptEssentials/TypeScriptEssentials.jsx @@ -16,11 +16,11 @@ import TsInstallation from './TsTopics/Introduction/TsInstallation'; import TsConfiguration from './TsTopics/Introduction/TsConfiguration'; // TypeScript Basics -// import WhatIsTypeScript from './TsTopics/TsBasics/WhatIsTypeScript'; -// import TypeAnnotations from './TsTopics/TsBasics/TypeAnnotations'; -// import BasicTypes from './TsTopics/TsBasics/BasicTypes'; -// import TypeInference from './TsTopics/TsBasics/TypeInference'; -// import TypeAssertions from './TsTopics/TsBasics/TypeAssertions'; +import WhatIsTypeScript from './TsTopics/TsBasics/WhatIsTypeScript'; +import TypeAnnotations from './TsTopics/TsBasics/TypeAnnotations'; +import BasicTypes from './TsTopics/TsBasics/BasicTypes'; +import TypeInference from './TsTopics/TsBasics/TypeInference'; +import TypeAssertions from './TsTopics/TsBasics/TypeAssertions'; // Advanced Types // import UnionTypes from './TsTopics/AdvancedTypes/UnionTypes'; @@ -111,12 +111,12 @@ const TypeScriptEssentials = () => { } /> } /> - {/* TypeScript Basics - Will be added in PR #3 */} - {/* } /> + {/* TypeScript Basics */} + } /> } /> } /> } /> - } /> */} + } /> {/* Advanced Types - Will be added in PR #4 */} {/* } />