【问题标题】:TypeScript result type based on parameter type基于参数类型的 TypeScript 结果类型
【发布时间】:2017-05-12 01:08:51
【问题描述】:

在此代码中,v1 的类型为BehaviorSubject<string | number>v2 的类型为{}

我希望v1 的类型为BehaviorSubject<string>v2 的类型为{ a: number, b: number }

TypeScript 类型系统可以实现这样的事情吗?

interface Test
{
    prop: {
        (x: string | number): BehaviorSubject<typeof x>;
        (x: {}): typeof x;
    }
}

let test: Test;
let v1 = test.prop('');
let v2 = test.prop({ a: 1, b: 2 });

即使使用 keyof 或映射类型功能,它也可能与最新的 TypeScript 2.1 一起使用。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    为此使用泛型怎么样?

    interface Test
    {
        prop: {
            <T extends string | number> (x: T): BehaviorSubject<T>;
            <T> (x: T): T;
        }
    }
    

    【讨论】:

      【解决方案2】:

      @Paarth 的解决方案回答了我的问题。我只需要使用:

      <T extends string> (x: T): BehaviorSubject<string>;
      <T extends number> (x: T): BehaviorSubject<number>;
      

      所以 prop(1) 具有与 prop(2) 兼容的类型(数字,而不是常量)。

      现在我想要这样的东西:

      interface Int
      {
          a: MyType<number>;
          b: MyType<string>;
          c: MyType<{ x: number, y: number }>;
      }
      

      使用相同的逻辑,其中a、b和c的类型分别为BehaviorSubject&lt;number&gt;, BehaviorSubject&lt;string&gt; and { x: number, y: number }

      这可能吗?

      【讨论】:

      • 您可能希望将此作为新问题发布以提高知名度
      猜你喜欢
      • 2018-08-28
      • 2023-03-30
      • 1970-01-01
      • 2020-10-27
      • 2022-11-04
      • 2023-02-22
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      相关资源
      最近更新 更多