TS定義陣列 ts宣告函式

前端小菜鸡美哥發表於2024-07-12

ts定義陣列

  // 定義整數型陣列
  const arr1: number[] = []
  const arr1_1: Array<number> = []

  // 定義字元竄型陣列
  const arr2: string[] = []
  const arr2_1: Array<string> = []

  // 定義物件型陣列
  const arr3: object[] = []
  const arr3_1: Array<Object> = []
  const arr3_2: Array<{ title: string; show: boolean; num?: number }> = []

  // 定義任意型別陣列
  const arr4: any[] = []
  const arr4_1: Array<any> = []
 
  //定義二維陣列型別(n維陣列類似)
  const arr5:Array<Array<any>> = []

如果型別比較多推薦使用介面去寫

interface Config {
  name: string;
  value: string;
  icon: string;
  occupancy?: number;
  detail?: string;
}


//const configs: Config[] =[]

 const configs: Config[] = reactive([
    {
      name: '記憶體',
      value: '',
      icon: memoryIcon,
    },
    {
      name: 'CPU',
      value: '',
      icon: cpuIcon,
    },
    {
      name: 'GPU',
      value: '',
      icon: gpuIcon,
    },
    {
      name: '資料盤硬碟使用量',
      value: '',
      occupancy: 0,
      icon: diskIcon,
    },
  ]);

ts宣告函式型別

// 語法一
function fn(param1:number,param2:string):string{
    if (param1 === 1){
        return param2
    }else {
        return "hello world"
    }
}

// 語法2
let fn2:(param1:number,param2:string) => string
fn2 = function(param1,param2){
    if (param1 === 1){
        return param2
    }else {
        return "hello world"
    }
}

相關文章