How to get Type of Array in Typescript generics

后端 未结 5 1934
半阙折子戏
半阙折子戏 2020-12-18 06:56

I have a method like this:

public select(fieldName: keyof TType)

Where TType could be an array type. In case of an array type

5条回答
  •  天涯浪人
    2020-12-18 07:21

    You will need a little helper to extract the boxed type:

    type Unboxed =
        T extends (infer U)[]
            ? U
            : T;
    

    Then your method can look like this:

    interface User {
        id: symbol;
        name: string;
    }
    
    class Foo {
        select(fieldName: keyof Unboxed) {
            console.log(fieldName) // "id" | "name"
        }
    }
    

    As to your extra question: yes, it's possible, but it may feel a bit strange.

    class Foo {
        select(fieldName: keyof Unboxed) {
            console.log(fieldName)
        }
    }
    
    new Foo()
      .select('addEventListener')
    

    Type parameters are meant to describe the arguments living inside the method or the generic type of the class. So perhaps you wanted to do the following:

    class Foo {
        select(fieldName: keyof Unboxed) {
            console.log(fieldName)
        }
    }
    
    new Foo()
      .select('addEventListener')
    

提交回复
热议问题