This content originally appeared on DEV Community and was authored by Fatima Alam
Intro:
- Superset of JavaScript.
- Object-oriented and tightly typed programming language.
- TypeScript code is transformed to JavaScript, which may be used in any environment that supports JavaScript,
- This including browsers, Node.js, and your own applications.
Array in TypeScript
Using square brackets ([]):
let numbers: number[] = [1, 2, 3, 4, 5];
let strings: string[] = ['a', 'b', 'c'];
Using the Array generic type:
let numbers: Array<number> = [1, 2, 3, 4, 5];
let strings: Array<string> = ['a', 'b', 'c'];
Mixed array types:
let mixed: (number | string)[] = [1, 'two', 3, 'four'];
Using a tuple (fixed length and types):
let tuple: [number, string, boolean] = [1, 'hello', true];
Disadvantages of TypeScript
- It takes a long time to compile TypeScript code.
- Abstract classes are not supported in TypeScript.
- Converting TypeScript to JavaScript requires an additional compilation step.
- Its type scheme is extremely complicated.
never and any
Key Differences
never:
Used for functions that do not return.
Represents a value that never occurs.
Useful for exhaustive type checking.
any:
Disables type checking for a variable.
Can hold any type of value.
Useful for migrating JavaScript to TypeScript or working with dynamic data
Tuples
// define our tuple
let ourTuple: [number, boolean, string];
// initialized incorrectly which throws an error
ourTuple = [false, 'Coding God was mistaken', 5];
// define our tuple
let ourTuple: [number, boolean, string];
// initialize correctly
ourTuple = [5, false, 'Coding God was here'];
// We have no type safety in our tuple for indexes 3+
ourTuple.push('Something new and wrong');
console.log(ourTuple);
New valueTuples only have strongly defined types for the initial values:
// define our readonly tuple
const ourReadonlyTuple: readonly [number, boolean, string] = [5, true, 'The Real Coding God'];
// throws error as it is readonly.
ourReadonlyTuple.push('Coding God took a day off');
Function
// the `: number` here specifies that this function returns a number
function getTime(): number {
return new Date().getTime();
}
Optional Parameter
// the `?` operator here marks parameter `c` as optional
function add(a: number, b: number, c?: number) {
return a + b + (c || 0);
}
Default Parameters
function pow(value: number, exponent: number = 10) {
return value ** exponent;
}
Object as an argument
function divide({ dividend, divisor }: { dividend: number, divisor: number }) {
return dividend / divisor;
}
Rest Paramter
function add(a: number, b: number, ...rest: number[]) {
return a + b + rest.reduce((p, c) => p + c, 0);
}
This content originally appeared on DEV Community and was authored by Fatima Alam
Fatima Alam | Sciencx (2024-07-25T01:34:22+00:00) TypeScript. Retrieved from https://www.scien.cx/2024/07/25/typescript-3/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.