JavaScript – 小技巧 Tips

1e6 等价于 1 + 后面 6 个零

console.log(1e6 === 1_000_000);

 

模拟 C# 的 Record Deconstruct

class Size implements Iterable<number> {
    constructor(
        public width : number, 
        public height: number
    ) {}

    *[Symbol.iterator]() {
        yield this.width;
        yield this.height
    }
}

const size = new Size(100, 200);

const [width, height] =  size; // 100, 200

利用 Iterable 可以让对象支持 Array 式 的 Deconstruct.

property 数量可控的情况下,这种方式会比 Object 式 的 Deconstruct 容易重命名。 

TypeScript 类型的问题 

虽然 Generator 可以让对象具有 Deconstruct 的能力,但是类型却并不是 Tuple。

上面例子中碰巧 width 和 height 都是 number 所以才可以这样写,如果是不同类型还是得写 deconstruct 方法。

像下面这样, firstName 的类型会是 string | number

const person = {
    firstName : 'Derrick',
    lastName : 'Yam',
    age: 11,

    *[Symbol.iterator]() {
        yield this.firstName;
        yield this.lastName;
        yield this.age;
    }
}

const [firstName, lastName, age] = person; 

我们只能另外写一个方法了

const person = {
    firstName : 'Derrick',
    lastName : 'Yam',
    age: 11,

    deconstruct() {
       return [this.firstName, this.lastName, this.age] as const;
    }
}
Object.defineProperty(person, 'deconstruct', {
    enumerable: false
});

 

Conditional add Property

function doSomething(num?: number) {
  const obj = {
    str: '',
    ...(num !== undefined && { num }),
  };
  console.log(obj);
}

doSomething(); // { str: '' } 没有 num 属性

 

posted @ 2023-09-03 16:35  兴杰  阅读(19)  评论(0编辑  收藏  举报