2
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
Acid Coder
  • 2,047
  • 15
  • 21

1 Answers1

1

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.

leonat
  • 127
  • 8
  • the already discussed issue here is different from my case, in the issue of your link, the excess member exists inside spread object and the "parent object" unable to trigger excess member check on that spread object(which is an issue I already faced and solved). In this case, the excess member exist outside of the spread object, spreading the object causes the "parent object" unable to trigger excess member check other property.**comment repost to fix some mistake** – Acid Coder Sep 07 '20 at 06:34