Acid Coder
Acid Coder

Reputation: 2746

typescript unable to trigger excess member check if spreading member of constrained typed

const abc =<T extends {res:{a:string}}>():T['res']=>{

    return {a:"1",b:1} // excess member, error as expected, ok
}

const abc2 =<T extends {res:{a:string}}>():T['res']=>{

    const c:T['res'] ={a:"1"}

    const d:T['res'] ={a:"1",b:"1"} // excess member, error as expected, ok

    return {...c,a:"1",b:1 } // no error eventhough with excess member, problem
}

const abc3 =<T extends {res:{a:string}}>():T['res']=>{

    type c = {res:{a:string}}

    const c:c['res'] ={a:"1"}

    return {...c,a:"1",b:1 } // excess member, error as expected, ok
}

abc and abc3 work expected

however abc2 is not what I expect

playground

my question:

  1. the reason abc2 unable to trigger excess member check
  2. proper way to do it

Upvotes: 2

Views: 53

Answers (1)

leonat
leonat

Reputation: 162

I would just comment but my reputation is to low, yet.

I think the example can be simplified to:

type ret = { a: string } 

const abc = ():ret =>{
    return {a:"1", b:"2"} // raises error as expected
}

const abc2 = ():ret =>{
    const t = {a:"1", b:"2"} 
    return t; // should raise error but doesn't
}

Link to playground

From my research this is an already discussed issue in the typescript community and due the fact that typescript is strucurally typed.

This is a nice solution for exactly typed function arguments, but i couldn't get it to work with return types.

Upvotes: 1

Related Questions