網站搜尋

如何從 TypeScript 的記錄類型中提取可變參數?


我有一個變數 x,定義如下:

function foo (a: string, ...nums: number[]): string {
  return a;
}
const x: Parameters<typeof foo>

// Inferred: const x: [string, ...number[]]

現在,我想提取字串和具有正確類型的數字。對於字串,我有:

const sExplicit: Parameters<typeof foo>[0] //easy to specify
const sInferred = x[0]                     //type inferred correctly

我想聲明一個變數來保存所有數字。我該怎麼做?

我嘗試了以下方法:

const numsExplicit: ??? Howto specify the type
const numsInferred = x.slice(1) // incorrectly inferred as (string | number)[]

答案#1

查找類型僅限於 number | string。

我會自己添加這個陣列:

function foo (a: string, ...nums: number[]): string {
 return a;
}
declare const x: Parameters<typeof foo>[1][];