Is there a way to “extract” the type of TypeScript interface property?

前端 未结 2 418
温柔的废话
温柔的废话 2020-12-07 13:56

Let\'s suppose there\'s a typing file for library X which includes some interfaces.

interface I1 {
    x: any;
}

interface I2 {
    y: {
        a: I1,
             


        
相关标签:
2条回答
  • 2020-12-07 14:05

    It wasn't possible before but luckily it is now, since TypeScript version 2.1. It has been released on the 7th of December 2016 and it introduces indexed access types also called lookup types.

    The syntax looks exactly like element access but written in place of types. So in your case:

    interface I1 {
        x: any;
    }
    
    interface I2 {
        y: {
            a: I1,
            b: I1,
            c: I1
        }
        z: any
    }
    
    let myVar: I2['y'];  // indexed access type
    

    Now myVar has type of I2.y.

    Check it out in TypeScript Playground.

    0 讨论(0)
  • 2020-12-07 14:14

    An interface is like the definition of an object. Then y is a property of your I2 object, that is of a certain type, in that case "anonymous".

    You could use another interface to define y and then use it as your y type like this

    interface ytype {
       a: I1;
       b: I1;
       c: I1;
    }
    
    interface I2 {
        y: ytype;
        z: any;
    }
    

    You can put your interface in a file and use extract so you can import it in other files of your projects

    export interface ytype {
       a: I1;
       b: I1;
       c: I1;
    }
    
    
    
     export interface I2 {
            y: ytype;
            z: any;
        }
    

    You can import it that way :

       import {I1, I2, ytype} from 'your_file'
    
    0 讨论(0)
提交回复
热议问题