Why does TS treat anonymous object differently then declared objects?

31 Views Asked by At

Somewhere in our code there was an extra property that shouldn't be there and I realized it was the result of a recent refactor. we refactored

foo({prop1: 1})

to

const props = {prop1: 1};
foo(props)

unfortunately somewhere along the way prop2 was added. pre-refactor this would error but post refactor there is no error

foo({prop1: 1, prop2: 1}) // Object literal may only specify known properties

const props = {prop1: 1, prop2: 1};
foo(props) // all good!?

Why does ts treat these two differently? I even tried

const props = {prop1: 1, prop2: 1} as const;
foo(props) // all good
food({...props}) // still all good

Here is a simplified example along with the things I tested

type OKType = {good: string}
interface OKInterface {good: string}

const test = (obj: {good: string}) => true;
const test1 = (obj: OKType) => true;
const test2 = (obj: OKInterface) => true;

// awsome
test({
    good: 'a',
    bad: 'a',
}) //error
test1({
    good: 'a',
    bad: 'a',
}) //error
test2({
    good: 'a',
    bad: 'a',
}) //error

// wtf
const a = {
    good: 'a',
    bad: 'a',
}
test(a) //good
test1(a) //good
test2(a) //good

ts-playground-link

is it possible to get the same type checking when passing a declared object into functions?

Seems like this has been answered here: Forcing excess-property checking on variable passed to TypeScript function

0

There are 0 best solutions below