Functions and Default Parameters
Create a TypeScript program that declares a function that takes two parameters, a string and a number. The function should log the string parameter repeated the number of times specified by the number parameter. If the number parameter is not provided, it should default to 3.
Write a function that takes in an array of objects with properties name
and age
, and returns only the objects where the person's age is greater than or equal to 18,
Create a TypeScript program that uses a generic function to reverse an array of strings, and takes a variable number of strings to the array using rest parameters. Provide an example of calling the function with a variable number of strings.
Create a TypeScript class called Person
that has private properties name and age, and a public method getDetails that returns a string with the person's name and age. Use parameter properties to define and initialize the properties in the constructor.
Create a TypeScript class called Student
that extends the Person class and has an additional private property grade. Define a public method getGrade that returns the student's grade. Use the super keyword to call the constructor of the Person class and initialize the name and age properties.
Create a TypeScript function that takes a parameter of type unknown and uses a type guard to check whether the parameter is of type string. If it is, log the string to the console. If it is not, log an error message.
- What is TypeScript, and how is it different from JavaScript?
- Can you explain the difference between "interface" and "type" in TypeScript?
- Can you give an example of how to use generics in TypeScript?
- What is the difference between an "unknown" and "any" type in TypeScript?
- Can you give an example of how to use enums in TypeScript?
- What is the "as" keyword used for in TypeScript?
- Can you explain how to use "type guards" with "in" and "typeof" operators in TypeScript?
Array and Tuple types
Create a TypeScript program that declares an array of strings and a tuple of a number and a string. Add elements to both data structures, and log them to the console.
Create a TypeScript program that uses a conditional type to create a new type that is either a string or a number, depending on whether a parameter of type string or number is passed to the function.
Then, create an interface for a person with properties name and age, and use the new type as a constraint on the age property.
Finally, create an object that satisfies the Person interface and log it to the console.
- Can you explain what a "tuple" is in TypeScript?
- Can you give an example of how to use "readonly" properties in TypeScript?
- Can you give an example of how to use "conditional types" in TypeScript?