相关疑难解决方法(0)

推断TypeScript中的函数参数

我正在尝试制作一个类型安全的映射函数(而不是下面的函数),但是我一直坚持获取要正确推断的函数参数。

    export type Mapper<U extends Unmapped> = {
      mapped: Mapped<U>
    };

    export type Unmapped = {
      [name: string]: (...args: any[]) => any
    };

    export type Mapped<U extends Unmapped> = {
      [N in keyof U]: (...args: any[]) => Promise<any>
    };

    const map = <U extends Unmapped>(unmapped: U): Mapper<U> => ({
      mapped: Object.entries(unmapped).reduce(
        (previous, [key, value]) => ({
          ...previous,
          [key]: (...args: any[]) => new Promise((resolve) => resolve(value(...args)))
        }),
        {}
      ) as Mapped<U>
    });

    const mapped = map({ test: (test: number) => test …
Run Code Online (Sandbox Code Playgroud)

typescript typescript-typings

7
推荐指数
2
解决办法
2517
查看次数

是否可以通过装饰器修改方法的返回类型?

假设我有一个A装饰器应用于返回字符串的方法。装饰器使用该字符串并最终返回B类型(一个类)。

class B {
  constructor(text: string) { ... }

  method() {...}
}

class X {
  @A
  someMethod(): string {
    return 'lalala';
  }
}
Run Code Online (Sandbox Code Playgroud)

装饰者

function A(target, property, descriptor) {
  const text: string = descriptor.value();

  descriptor.value = () => new B(text);
}
Run Code Online (Sandbox Code Playgroud)

发生了什么?现在someMethod返回一个B对象而不是字符串。但我不能做这样的事情:

class X {
  constructor() {
    this.someMethod().method();
  }

  @A
  someMethod(): string {
    return 'lala';
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么?因为someMethod从定义中是字符串类型,但装饰器使其返回B类型。我可以以某种方式让打字稿知道someMethod实际上返回B,而不是string

decorator typescript

5
推荐指数
1
解决办法
4849
查看次数

使用 TypeScript 类型系统创建流畅、有状态的构建器

我想创建一个可以代表builder.a().b().build()or 的构建器builder.b().a().build(),但不能代表builder.a().build(), builder.b().build()orbuilder.a().a().build()等​​。

显然我可以在构建方法中进行验证,但我希望编译器对此进行提示(并让 vs code 提供自动完成功能)。我认为 TS 类型系统可以使用映射类型、并集和交集来表示这一点,但我不太明白。

有谁知道我该怎么做?

typescript

5
推荐指数
1
解决办法
2103
查看次数

标签 统计

typescript ×3

decorator ×1

typescript-typings ×1