Typescript generic type check not working as expected

前端 未结 3 1061
孤独总比滥情好
孤独总比滥情好 2021-01-21 13:48

I have made a simple test fixture:

export interface ITest1 {}
export interface ITest2 {}
export interface ITestGeneric {}

export function test() {
  le         


        
3条回答
  •  一个人的身影
    2021-01-21 14:05

    This is because typescript uses structural compatibility to determine if two types are compatible. In your case since ITestGeneric has no members, it is basically compatible with anything. If you start adding properties, incompatibilities will quickly appear:

    export interface ITest1 { t1: string}
    export interface ITest2 { t2: number}
    export interface ITestGeneric { value: T}
    
    export function test() {
        let p: ITestGeneric = {} // error
        let q: ITestGeneric = p; // error
    }
    

    You can read more about type compatibility in typescript here

提交回复
热议问题