Posts > TS Basic: Everyday Types

TS Basic: Everyday Types

The Primitives: string, number & boolean

  • same as JS typeof values

string - “hello”

number

  • number values eg. 42
  • no int or float just numbers

boolean

  • two values true or false

Arrays

number[]

  • array of numbers
  • number[1,2,3]
  • Array<number>

string[]

  • array of string
  • string['bbq','pizza','coke']
  • Array<string>

any

  • special type that you can use wherever you don’t want a particular value to cause type checking error
  • using any disable all further type checking and it assumed you know the environment better than TS
let obj: any = {x:0}
  • useful when you don’t want to write out a long type just to convince TS that a particular line of code is okay

null and undefined

  • same as JS null and undefined TS null and undefined behave depending on whether strictNullCheck option is on / off

void

  • a function that does not return any value
  • if you don’t specify and explicit return type and the function DOES NOT HAVE a return statement. The inferred return type would be 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

Object

  • refers to any value that isn’t primitive

unknown

  • the unknown type represents any value
  • similar as type any but is safer because it’s not legal to do anything w/ an unknown value
  • stricter type checking
  • the type unknown is often used in scenarios where the type is not known ahead of time or when working with dynamic type values
  • it provides a way to assign any values to a variable without losing type safety
function 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

  • represents the value which is never observed
  • in return type this means that the function throws an exception or terminates the execution of the program
  • never also appears when TS determines that there’s nothing left in a union
function fn(x: string | number){
	if(typeof x === 'string'){

	}else if(typeof x === 'number'){

	}else{
		x //has type never
	}
}

Tags 🏷