class Cat {
static let numberOfLegs = 4
func makeSound() {
print("meow")
}
}
class Dog {
static let numberOfLegs = 4
func makeSound() {
print("woof")
}
}
var animal = Dog();
// error: cannot assign value of
// type 'Cat' to type 'Dog'
animal = Cat();
class Cat {
static numberOfLegs = 4;
makeSound() {
console.log("meow")
}
}
class Dog {
static numberOfLegs = 4;
makeSound() {
console.log("woof")
}
}
let animal = new Dog()
animal = new Cat() // No error
class Cat {
static numberOfLegs = 4;
makeSound() {
console.log("meow")
}
scratchFurniture() {
}
}
class Dog {
static numberOfLegs = 4;
makeSound() {
console.log("woof")
}
}
let animal = new Dog()
animal = new Cat() // No error
Even if you've never written a generic type or function, you have used them.
const numbers = [1, 2, 3];
// TypeScript knows doubled is an array
// of numbers (number[])
const doubled = numbers.map((num) => num * 2);
// TypeScript infers the types of accumulator and
// currentValue as numbers
const sum = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue,
0
);
Code Example
Current Issues with our Implementation
Template literal types allow us to combine string literals
TypeScript will create a new union which applies the template literal type to each member of a union
It works with multiple unions
Don't over complicate this one, it's just a way to look up a specific property on another type
These are similar to JavaScript/TypeScript
We haven't used them yet however...
Top Type: Contains all types, meaning any other type is assignable to it.
TypeScript has two top types any and unknown
Bottom Type: Nothing is assignable to it except itself
TypeScript has one bottom type never
Let's focus on bottom types and look at what happens when we combine it with other types
Conditional types act exactly as conditional statements do in programming
When given a union, conditional types distribute the condition to each member of the union
"Hey if it matches this pattern, infer what it is and give me a variable to refer to it by"
Current Issues with our Implementation
Create a union of path params
Pull out the path params in a dev friendly way
We have a path we need to break it into segments
Create an object type out of a union of a key types
string | number | symbol
Let's Keep in Touch, I'm David Nicholas
Slides: https://davidnic11.github.io/talk-advanced-typescript/
Example Repo: https://github.com/DavidNic11/examples-advanced-typescript
LinkedIn: