TypeScript 解構和展開


解構數組

  • 解構數組元素
let input = [1, 2];
let [first, second] = input;
console.log(first,second);
  • 交換值
[first, second] = [second, first];
  • 函數參數解構
function f([first, second]: [number, number]){
    console.log(first,second);
}

f([1,2]);
  • 剩余變量
let [first, ...rest] = [1,2,3,4];
console.log(first,rest);
  • 忽略尾隨元素
let [first] = [1,2,3,4];
console.log(first);
  • 忽略其他元素
let [, second, , fourth] = [1,2,3,4];
console.log(second,fourth);

解構元組

  • 解構元組元素
let tuple: [number, string, boolean] = [7, "hello", true];
let [a, b, c] = tuple;
  • 剩余元素
let [a, ...bc] = tuple;
let [a,b,c, ...d] = tuple;
  • 忽略末尾元素或其他元素
let [a] = tuple;
let [, b] = tuple;

對象解構

  • 解構對象屬性
let o = {
    a: "foo",
    b: 12,
    c: "bar"
}

let {a, b} = o;
  • 解構賦值
({a, b} = {a:"baz",b:101});
  • 剩余變量
let {a, ...passthrough} = o;
let total = passthrough.b + passthrough.c.length;
  • 解構屬性重命名
let {a:newName1, b:newName2} = o;
  • 解構並指定類型
let {a, b}: {a:string, b:number} = o;
  • 解構並賦予默認值
function keepWholeObject(wholeObject: {a:string, b?:number}){
    let {a,b = 1001} = wholeObject;
}

函數聲明解構

  • 函數聲明解構
type C = {a:string, b?: number}
function f({a,b}: C): void{
}
  • 指定默認值
function f({ a="", b = 0} = {} ): void{
}

f();

function f({a,b = 0 } = {a: "" }): void {
}

展開數組

  • 數組元素展開
let first = [1, 2];
let second = [3, 4];
let bothPlus = [0, ...first, ...second, 5];
  • 對象展開
let defaults = {food: "spicy" ,price : "$$" , ambiance: "noisy" };
let search = {...defaults, food: "rich" };
  • 對象展開(但布包含方法)
class C {
    p = 12;
    m() {
    }
}

let c = new C();
let clone = {...c};
clone.p;
clone.m(); // error!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM