≪ Today I learned.
RSS購読
    公開日
    タグ
    TypeScript
    著者
    ダーシノ

    TypeScript 5.0 Betaがリリースされた

    TypeScript 5.0 Betaがリリースされた。

    Decorators

    クラスやメソッドなどの上に@xxxxと書いて機能拡張できる機能

    デコレータ

    function logged(originalMethod: any, _context: any) {
        function replacementMethod(this: any, ...args: any[]) {
            console.log("LOG: Entering method.")
            const result = originalMethod.call(this, ...args);
            console.log("LOG: Exiting method.")
            return result;
        }
        return replacementMethod;
    }

    使用方法

    class Person {
      @logged
      greet() {
        console.log(`Hi, my name is ${this.name}`)
      }
    }
    
    const person = new Person('john smith')
    person.greet()
    // LOG: Entering method.
    // Hi, my name is john smith
    // LOG: Exiting method.

    const type Parameters

    Before

    type HasNames = { readonly names: string[] };
    function getNamesExactly1<T extends HasNames>(arg: T): T["names"] {
      return arg.names;
    }
    // string[]
    const names1 = getNamesExactly1({ names: ["Alice", "Bob", "Eve"]});

    After

    function getNamesExactly2<const T extends HasNames>(arg: T): T["names"] {
      return arg.names;
    }
    // readonly ["Alice", "Bob", "Eve"]
    const names2 = getNamesExactly2({ names: ["Alice", "Bob", "Eve"]} as const);