【问题标题】:Is there a way to make inference work with extended string in conditional typescript?有没有办法在条件打字稿中使用扩展字符串进行推理?
【发布时间】:2019-03-28 01:12:43
【问题描述】:

我正在尝试提取通用字符串文字类型,但打字稿推断只返回类型字符串。

所以从技术上讲,一旦将字符串文字类型传递给函数,我们就不能再提取它了。

type Key<T extends string> = { key: T };

declare function getKey<T extends string>(key: T): Key<T>;

let someKey = getKey('check');

declare function updateWithKey<T, K extends string>(key: T): T extends Key<K> ? K : never;

let someUpdatedKey = updateWithKey(someKey); // Shouldn't be 'check'?

这是Playground中的代码

【问题讨论】:

    标签: typescript inference


    【解决方案1】:

    updateWithKey 中,K 不会出现在编译器可以自动推断的位置,因此它被视为允许的最通用类型,即string

    但条件类型have special syntax 告诉编译器您希望推断出实际类型:

    type Key<T extends string> = { key: T };
    
    declare function getKey<T extends string>(key: T): Key<T>;
    
    let someKey = getKey('check');
    
    declare function updateWithKey<T>(key: T): T extends Key<infer K> ? K : never;
    
    let someUpdatedKey = updateWithKey(someKey); // let someUpdatedKey: "check"
    

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 2021-06-18
      • 1970-01-01
      • 2011-09-05
      • 2019-06-27
      • 2018-07-25
      • 2019-06-26
      • 1970-01-01
      • 2020-07-07
      相关资源
      最近更新 更多