連結

TypeScript 如何給予型別

cheat sheet


const a:number = 12

// number boolean string null undefined

const arr:number[] = [1,2,3]
const arr:Array<number> = [1,2,3]

const typeAny:any = '';
// 可以為任意值
// 可以在 config 設定是否使用 noImplicitAny: false 

const un:unknow = '';

Array.isArray(arr)
typeof str === "string"
type Obj = {
	id:number,
	name:string
}

interface Obj {
	id:number,
	name:string
}

Differences Between Type Aliases and Interfaces

function func(a:string, num?:number): string | number => {
	return ''
}

// ok
func('a', 12)

// ok
func('a')

// return undefined or not return
function func():void =>{
	
}

// 
function func():never => {
	throw Error()
}

// Promise
async function getFavoriteNumber(): Promise<number> {
  return 26;
}

type as const

const req = { url:'https://...', methods:"GET" } as const

// req
const req:{
	readonly url:'https://...',
	readonly methods:"GET"
}