איך לחלץ ארגומנט varargs מסוג רשומה ב-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

סוג החיפוש הוא לפי מספר | מחרוזת בלבד.

הייתי מוסיף את המערך בעצמי:

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