Introduction to TypeScript's Builtin Data Types and Functions

TypeScript, a superset of JavaScript, brings static typing to the dynamic world of JavaScript. This feature not only enhances code readability but also helps catch errors early in the development process. At the core of TypeScript are its built - in data types and functions, which are essential for writing robust and efficient code. In this blog post, we will explore these built - in data types and functions, their core concepts, typical usage scenarios, and best practices.

Table of Contents

  1. Built - in Data Types
    • Primitive Data Types
    • Object Data Types
  2. Built - in Functions
    • String Functions
    • Array Functions
    • Number Functions
  3. Typical Usage Scenarios
    • Form Validation
    • Data Manipulation
  4. Best Practices
    • Type Annotations
    • Function Overloading
  5. Conclusion
  6. FAQ
  7. References

Detailed and Structured Article

Built - in Data Types

Primitive Data Types

  • Number: Represents both integer and floating - point numbers. For example:
let num: number = 10;
let floatNum: number = 10.5;
  • String: Used to represent textual data. It can be defined using single quotes, double quotes, or backticks (for template literals).
let str: string = 'Hello';
let templateStr: string = `Hello, ${str}`;
  • Boolean: Has only two possible values: true or false.
let isDone: boolean = false;
  • Null and Undefined: null represents the intentional absence of any object value, while undefined is the value given to variables that have been declared but not assigned a value.
let nullVar: null = null;
let undefinedVar: undefined = undefined;
  • Symbol: A unique and immutable primitive value, often used as an identifier for object properties.
const sym = Symbol('key');

Object Data Types

  • Array: Used to store multiple values of the same or different types.
let numArray: number[] = [1, 2, 3];
let mixedArray: (number | string)[] = [1, 'two', 3];
  • Tuple: A fixed - length array where each element can have a different type.
let person: [string, number] = ['John', 30];
  • Enum: Allows you to define a set of named constants.
enum Color {
    Red,
    Green,
    Blue
}
let myColor: Color = Color.Green;
  • Any: Represents any type. It can be used when you don’t know the type of a variable at compile - time.
let unknownVar: any = 'This could be anything';

Built - in Functions

String Functions

  • toUpperCase() and toLowerCase(): Convert a string to uppercase or lowercase respectively.
let str = 'hello';
let upperStr = str.toUpperCase(); // 'HELLO'
let lowerStr = upperStr.toLowerCase(); // 'hello'
  • substring(): Extracts a part of a string.
let fullStr = 'Hello World';
let subStr = fullStr.substring(0, 5); // 'Hello'

Array Functions

  • push() and pop(): push() adds one or more elements to the end of an array, and pop() removes the last element from an array.
let numArray: number[] = [1, 2, 3];
numArray.push(4); // [1, 2, 3, 4]
let lastNum = numArray.pop(); // 4
  • map(): Creates a new array with the results of calling a provided function on every element in the calling array.
let numArray: number[] = [1, 2, 3];
let squaredArray = numArray.map(num => num * num); // [1, 4, 9]

Number Functions

  • toFixed(): Formats a number using fixed - point notation.
let num = 10.5678;
let fixedNum = num.toFixed(2); // '10.57'
  • isNaN(): Determines whether a value is NaN.
let nanCheck = isNaN(NaN); // true

Typical Usage Scenarios

Form Validation

When building web forms, TypeScript’s data types and functions can be used to validate user input. For example, you can use the number type to ensure that a field only accepts numeric values and use string functions to check the length of a password.

function validateForm(name: string, age: number) {
    if (name.length < 3) {
        return false;
    }
    if (age < 18) {
        return false;
    }
    return true;
}

Data Manipulation

In applications that deal with large amounts of data, TypeScript’s array functions can be used to filter, sort, and transform data. For example, you can use the filter() function to get all the even numbers from an array.

let numArray: number[] = [1, 2, 3, 4, 5, 6];
let evenNumbers = numArray.filter(num => num % 2 === 0); // [2, 4, 6]

Best Practices

Type Annotations

Always use type annotations to make your code more readable and maintainable. For example, instead of using the any type, try to be as specific as possible.

// Good practice
let age: number = 30;
// Bad practice
let ageAny: any = 30;

Function Overloading

Function overloading allows you to define multiple function signatures for a single function. This can make your code more flexible and easier to understand.

function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
    return a + b;
}

Conclusion

TypeScript’s built - in data types and functions are powerful tools that can significantly improve the quality and reliability of your code. By understanding these core concepts, typical usage scenarios, and best practices, intermediate - to - advanced software engineers can write more efficient and maintainable code. Whether you are building web applications, desktop applications, or even server - side applications, TypeScript’s features will prove to be invaluable.

FAQ

  1. Can I use TypeScript’s built - in functions with JavaScript code?
    • Yes, since TypeScript is a superset of JavaScript, you can use most of the built - in functions in JavaScript code. However, you need to compile TypeScript code to JavaScript before running it in a JavaScript environment.
  2. What is the difference between let and var in TypeScript?
    • let has block - scoped variables, while var has function - scoped variables. This means that variables declared with let are only accessible within the block in which they are defined, while variables declared with var are accessible throughout the function.
  3. When should I use the any type?
    • You should use the any type when you are migrating existing JavaScript code to TypeScript or when you are working with third - party libraries that do not have type definitions. However, it is recommended to use more specific types whenever possible.

References