Some examples here
- Dynamic types are very similar to functions
- You can use a map/array as type so you can reuse it for function params using
as const
- You can Pick/Omit properties of an interface
- You can create conditional types that has different properties depending of a type
- You can select (and reuse) a property type of an interface with
Interface["propertyName"]
- You can save type the return of a function by infering it
ReturnType<typeof myFunction>
interface DynamicType<IdType> {
id: IdType,
title: string,
}
interface Book extends DynamicType<string> {
publishedYear: number
}
const myBook: Book = {
id: "5",
title: "Lord of the rings: Fellowship of the ring",
publishedYear: 1954
}
const ANIMAL_TYPES = {
DOG: "dog" as const,
SNAKE: "snake",
} as const
const ANIMAL_TYPES_VALUES = Object.values(ANIMAL_TYPES);
type AcceptedAnimalTypes = typeof ANIMAL_TYPES_VALUES[number]
interface Animal<AcceptedAnimalTypes> {
animalType: AcceptedAnimalTypes,
name: string,
sound: string,
eyes: number,
legs: number,
}
interface Dog extends Animal<typeof ANIMAL_TYPES.DOG> { }
interface Snake extends Omit<Animal<typeof ANIMAL_TYPES.SNAKE>, "legs"> {
termalViewCallback: (elementsSeen: number) => void
}
const myAnimals: Array<Dog | Snake> = [
{ animalType: ANIMAL_TYPES.DOG, name: "toby", sound: "guau guau", eyes: 2, legs: 4 },
// { animalType: "snake", name: "devil", sound: "guau guau", eyes: 2, legs: 4 },
{
animalType: ANIMAL_TYPES.SNAKE,
name: "devil",
sound: "shhhh",
eyes: 2,
termalViewCallback: (elementsSeen => console.log(`I see with my termal vission ${elementsSeen} elements`))
},
]
function callMyAnimals() {
for (const animal of myAnimals) {
const { animalType, sound } = animal
const animalRespondToMe = () => console.log(sound)
animalRespondToMe()
const isSnake = animalType === ANIMAL_TYPES.SNAKE
if (!isSnake) continue
const { termalViewCallback: tellMeHowManyElementsYouSee } = animal
tellMeHowManyElementsYouSee(5)
}
}
// callMyAnimals()
function getAllBooksIds() {
return [myBook].map(({ id, title }) => ({id, title}))
}
type getAllBookIdsResult = ReturnType<typeof getAllBooksIds>
const booksIds = getAllBooksIds()
function fetchBooksIds(ids: ReturnType<typeof getAllBooksIds>) {
for (const {id, title} of ids) {
console.log(`id ${id} and the title is "${title}"`)
}
}
fetchBooksIds(booksIds)