簡體   English   中英

解構函數參數對象並......休息

[英]Destructuring a function parameter object and …rest

我想編寫一個函數,它接受一個對象參數並捕獲一個變量中的所有剩余參數。 目標是允許函數接收命名參數(與位置參數相反),其中一些是可選的,並在函數中設置默認值。 所以,在偽代碼中是這樣的:

interface IMyProps {
  a: string
  b?: number
}

const myfun1 = (p: {a: string, b?:number, ...rest}) => {
  const {a, b = 'hello'} = p;
}

在 Typescript 2.0 中實現這一目標的最佳方法是什么?

您可以直接在函數參數中使用解構賦值:

interface IMyType { 
    a: number;
    b: number;
    c: number;
    d: number;
    [k: string]: number; // use this if you don't know the name of the properties in 'rest'
}

const obj: IMyType = { a: 1, b: 2, c: 3, d: 4 }

// Normal destructuring
const { a, b, ...rest } = obj;
console.log(rest); // {c: 3, d: 4}

// Directly in function arguments
const fn = ({ a, b, ...rest }: IMyType) => { console.log(rest); }

console.log(fn(obj)); // {c: 3, d: 4}

更新:

鑒於microsoft/TypeScript#28312的 PR,您現在可以使用泛型,如下所示:

const myfun1 = <T extends IMyProps>(p: T) => {
    const { a, b = 'hello', ...rest } = p;
    a; // string
    b; // number | 'hello'
    rest; // const rest: Pick<T, Exclude<keyof T, "a" | "b">>
}

其中rest變量被推斷為類型Omit<T, "a" | "b"> Omit<T, "a" | "b"> ,這可能是您想要的。


前 TS4 答案

如果您已經取消了所有顯式命名的屬性,我認為在 TypeScript 中使用 rest 運算符進行對象解構對應於解構對象類型的索引簽名 這意味着您將有相同的限制,其中其余屬性的類型必須至少與所有顯式標記屬性的並集一樣寬。 在您的情況下,您可以使用如下索引簽名擴展IMyProps

interface IMyPropsWithIndex {
  a: string
  b?: number
  [k: string]: string | number | undefined
}

自的類型astring的類型和bnumber | undefined number | undefined 您可以向聯合添加更多內容,但不能使其更窄,例如string 如果這對您沒問題,那么進行解構的方法將是這樣的:

const myfun1 = (p: IMyPropsWithIndex) => {
  const { a, b = 'hello' , ...rest } = p;
  a; // string
  b; // number | 'hello'
  rest; // {[k: string]: string | number | undefined}
}

如果你檢查變量的類型,你會得到類似上面的內容。


Playground 鏈接到代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM