【问题标题】:Capturing generic parameters in mapped types捕获映射类型中的泛型参数
【发布时间】:2019-12-03 23:08:18
【问题描述】:

在打字稿中,我想使用不属于签名的通用参数。例如,我想要一些类似下面的代码...

type NotArray<T> = T extends Array<I> ? I: T;
type Test1 = NotArray<Array<number>>; // Resolves to 'number'
type Test2 = NotArray<string>> // Resolves to 'string'

使用Cannot find name 'I'. 编译失败如果我将I 更改为any,它将编译,但解析的类型是any。例如:

type NotArray<T> = T extends Array<any> ? any: T;
type Fail = NotArray<Array<number>>; // Resolves to 'any'

有没有办法将泛型参数“捕获”到数组中?

【问题讨论】:

    标签: typescript generics mapped-types


    【解决方案1】:

    只需在I 定义之前添加infer 关键字:

    type NotArray<T> = T extends Array<infer I> ? I: T;
    type Test1 = NotArray<Array<number>>; // Resolves to 'number'
    type Test2 = NotArray<string> // Resolves to 'string'
    

    Type inference in conditional types

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-26
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    相关资源
    最近更新 更多