Posts > TS Basic: Everyday Types
June 16, 2023
typeof
valuesstring
- “hello”
number
int
or float
just numbersboolean
true
or false
number[]
number[1,2,3]
Array<number>
string[]
string['bbq','pizza','coke']
Array<string>
any
any
disable all further type checking and it assumed you know the environment better than TSlet obj: any = {x:0}
null
and undefined
strictNullCheck
option is on / offvoid
void
//example of a void function
function greet(){
console.log('hello');
}
//annotated function `:void`
function greet(): void {
console.log('hello');
}
👌explicitly annotating the return type void
adds clarify and is a good practice for readability and maintainability
unknown
unknown
type represents any valueany
but is safer because it’s not legal to do anything w/ an unknown valueunknown
is often used in scenarios where the type is not known ahead of time or when working with dynamic type valuesfunction processValue(value: unknown){
if(typeof value === 'string'){
//your code
}else if (typeof value === 'number'){
//your code
}else{
//your code
}
}
👌when working on type unknown
you’ll need to perform type checks or type assertion before you can use them as specific type. This is because TSC doesn’t have enough information to determine the exact type of the unknown value without additional checks.
// setting dynamic data as `unknown`
async function fetchData(): Promise<unknown> {
//fetching data code
}
//fetching data if you know what the type is
interface UserData {
id: number,
name: string,
email: string,
}
async function fetchData(): Promise<UseData>{
//rest of your code
}
👌by defining explicit type you make your codebase more maintainable
never
observednever
also appears when TS determines that there’s nothing left in a unionfunction fn(x: string | number){
if(typeof x === 'string'){
}else if(typeof x === 'number'){
}else{
x //has type never
}
}