What are the key syntax differences between TypeScript and JavaScript, and could you provide an illustrative example with an explanation?
TypeScript and JavaScript share many similarities, but TypeScript introduces additional syntax due to its static typing features. Here are some key syntax differences:
Variable Declaration with Types:
- JavaScript: Variables are declared without specifying types.
javascriptlet variableName = 10;
- TypeScript: Variable types can be explicitly defined.
typescriptlet variableName: number = 10;
Function Parameters and Return Types:
- JavaScript: Function parameters and return types are not explicitly typed.
javascriptfunction add(a, b) {
return a + b;
}- TypeScript: Types for parameters and return values can be specified.
typescriptfunction add(a: number, b: number): number {
return a + b;
}Interfaces and Type Annotations:
JavaScript: No built-in support for interfaces.
TypeScript: Interfaces can be defined to enforce a specific structure.
typescriptinterface Person {
name: string;
age: number;
}
function getPersonInfo(person: Person): string {
return `Name: ${person.name}, Age: ${person.age}`;
}Enum:
JavaScript: Enums are not natively supported.
TypeScript: Enums can be used to define named constant values.
typescriptenum Direction {
Up,
Down,
Left,
Right
}
let userDirection: Direction = Direction.Up;
These examples highlight some of the syntax differences between TypeScript and JavaScript, showcasing how TypeScript introduces static typing and other features to enhance code maintainability and developer experience.
0 মন্তব্যসমূহ