TypeScript is a typed language that allows you to specify the type of variables, function parameters, returned values, and object properties.
Here an advanced TypeScript Types cheat sheet with examples.
Let’s dive in.
An intersection type is a way of combining multiple types into one. This means that you can merge a given type A with a type B or more and get back a single type with all properties.
type LeftType = {
id: number
left: string
}
type RightType = {
id: number
right: string
}
type IntersectionType = LeftType & RightType
function showType(args: IntersectionType) {
console.log(args)
}
showType({ id: 1, left: "test", right: "test" })
// Output: {id: 1, left: "test", right: "test"}
As you can see, IntersectionType
combines two types - LeftType
and RightType
and uses the &
sign to construct the intersection type.
Union types allow you to have different types annotation within a given variable.
type UnionType = string | number
function showType(arg: UnionType) {
console.log(arg)
}
showType("test")
// Output: test
showType(7)
// Output: 7
The function showType
is a union type that accepts both strings and numbers as a parameter.
A generic type is a way of reusing part of a given type. It helps to capture the type T
passed in as a parameter.
function showType<T>(args: T) {
console.log(args)
}
showType("test")
// Output: "test"
showType(1)
// Output: 1
To construct a generic type, you need to use the brackets and pass T
as a parameter.
Here, I use T
(the name is up to you) and then, call the function showType
twice with different type annotations because it’s generic - it can be reused.
interface GenericType<T> {
id: number
name: T
}
function showType(args: GenericType<string>) {
console.log(args)
}
showType({ id: 1, name: "test" })
// Output: {id: 1, name: "test"}
function showTypeTwo(args: GenericType<number>) {
console.log(args)
}
showTypeTwo({ id: 1, name: 4 })
// Output: {id: 1, name: 4}
Here, we have another example that has an interface GenericType
which receives a generic type T
. And since it’s reusable, we can call it first with a string and then a number.
interface GenericType<T, U> {
id: T
name: U
}
function showType(args: GenericType<number, string>) {
console.log(args)
}
showType({ id: 1, name: "test" })
// Output: {id: 1, name: "test"}
function showTypeTwo(args: GenericType<string, string[]>) {
console.log(args)
}
showTypeTwo({ id: "001", name: ["This", "is", "a", "Test"] })
// Output: {id: "001", name: Array["This", "is", "a", "Test"]}
A generic type can receive several arguments. Here, we pass in two parameters: T
and U
, and then use them as type annotations for the properties. That said, we can now use the interface and provide different types as arguments.
#typescript #javascript #angular #developer