Skip to content

Instantly share code, notes, and snippets.

@K3ndev
Last active May 16, 2023 02:28
Show Gist options
  • Save K3ndev/3d9cd17d7e6d2721f6f9934484af2650 to your computer and use it in GitHub Desktop.
Save K3ndev/3d9cd17d7e6d2721f6f9934484af2650 to your computer and use it in GitHub Desktop.

Typescript primitives

  • boolean
  • string
  • number
  • undefined
  • null
  • any
  • unkown
  • never
  • void
  • bigint
  • symbol

return type

// this is enforce
const returnSomething = (a: number, b:number):number => {
  return a + b
}

infered type

const returnSomething = (a: number, b:number) => {
  return a + b
} 
// typescript know that this function is a number

type

  • type is more flexible than interface
type fooType = {
  foo: string
}
type todoType = fooType &{
  userId: number
  id: number
  title: string
  completed: boolean
}


const fetchSomething = async(id: number): Promise<todoType> => {
  const res = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
  const data = await res.json() as todoType // casting, this is overide not enforce 
  return data
}
(async() => {
    fetchSomething(1).then((data) => {
        console.log(data)
    })
})()

interfaces

interface fooType {
  foo: string
}
interface todoType extends fooType{
  userId: number
  id: number
  title: string
  completed: boolean
}

generics

  • for dynamic types
type APIResponseType<T> = {
    message: string
    results: T
}
type UserType = {
    id: number
    name: string
}


const fetchUsers = ():APIResponseType<UserType> => {
    const results = {id: 1, name: 'foo' }
    return {message: 'Success', results} as APIResponseType<UserType>
}

utilities

type UserType = {
    id: string
    name: string
    age?: number
    email: string
}
// ? optional

// this will become like user but without id and email
type CreateUser = Omit<UserType, 'id' | 'email'>

// all of the UpdateUser become optional
type UpdateUser = Partial<Omit<UserType, 'id'>>

// only name
type SomethingUser = Pick<UserType, 'name' | 'email'>

// this will remove ? optional, all of them become required
type SomethingUser2 = Required<UserType>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment