30
loading...
This website collects cookies to deliver better user experience
let item: Item = {...}
type Item = {
name: string
}
type FileItem = Item & {
extension: string
}
// We know for sure that item
// is also a file
printFile(item as File)
type Car = {
numOfDoors: number
}
type Airplane = {
numOfEngines: number
}
const car: Car = {numOfDoors: 5}
// Conversion of type 'Car' to type 'Airplane' may be a mistake
// because neither type sufficiently overlaps with the other.
const airplane = car as Airplane
unknown
or any
.unknown
because is the universal setany
because disables the type checking
const airplane = car as unknown as Airplane
type Car = {
numOfDoors: number
numOfAirbags: number
}
// Error: Property 'numOfAirbags' is missing
const car: Car = {numOfDoors: 5}
// No error
const car = {numOfDoors: 5} as Car
as const
is used to hint the type system about values being immutable.const coolBands = ['Oasis', 'AC/DC', 'Foo Fighters'] as const
// type CoolBands = "Oasis" | "AC/DC" | "Foo Fighters"
type CoolBands = typeof coolBands[number]
const coolBandsAndSingers = {
'Oasis': 'Liam Gallagher',
'AC/DC': 'Brian Johnson',
'Foo Fighters': 'Dave Grohl'
} as const
// type CoolBands = "Oasis" | "AC/DC" | "Foo Fighters"
type CoolBands = keyof typeof coolBandsAndSingers
// type CoolSingers = "Liam Gallagher" | "Brian Johnson" | "Dave Grohl"
type CoolSingers = typeof coolBandsAndSingers[CoolBands]
String
or Number
exist and wonder if you should use them as types.string
, number
, boolean
, etc.// charAt is not a property of
// the string primitive
"hey".charAt(1)
string
primitive in String
under the hood and uses the charAt
method of String
and then throws that object away.// These wrappers don't have behave
// as primitives
new String('hey') === new String('hey')
'hey' === new String('hey')