0

I noticed that when creating an interface, if you then create an object of that type, you must include all the properties:

interface twoProps {
    first: number;
    // second: string;
}

const a: twoProps = {
    first: 5,
    second: 'fgfg'
}

This will show an error, because second shouldn't be a part of a.

However when creating a function with an argument of that interface, you can pass an object that doesn't necessarily have all the properties:

interface twoProps {
    first: number;
    // second: string;
}

const a = {
    first: 5,
    second: 'fgfg'
}

function run (a: twoProps): void {
    console.log('running')
}

run(a) 

Here we won't get an error. What is the reasoning behind this difference?

sir-haver
  • 3,096
  • 7
  • 41
  • 85
  • 1
    Seems like a duplicate of [Why am I getting an error "Object literal may only specify known properties"?](https://stackoverflow.com/questions/31816061/why-am-i-getting-an-error-object-literal-may-only-specify-known-properties). See https://jorgedacostaza.gitbook.io/typescript-pt/type-system/freshness and https://github.com/Microsoft/TypeScript/issues/3755 – Emma Apr 18 '22 at 17:18
  • No because I asked why if we pass that object as argument of that type we won't get an error, that is my question, why this DIFFERENCE – sir-haver Apr 18 '22 at 17:22
  • 1
    Option 2 is allowed by typescript because that's the way typescript does inheritence. The object is compatible with the type, it's just an extended version of the type. Option 1 results in an error because for that specific case (initializing a variable), typescript does a stricter check. They do this stricter check because the code you wrote would almost always be a mistake. – Nicholas Tower Apr 18 '22 at 17:22
  • Ok so it just assumes it should be less strict in case of function arguments? I see thank you for your help – sir-haver Apr 18 '22 at 17:24
  • 1
    Yes, though i would describe the looser version as the default. For specific cases they do stricter checks. – Nicholas Tower Apr 18 '22 at 17:26
  • 2
    @sir-haver the reduced strictness is not because TypeScript is specifically less strict on function arguments, rather because passing a value into a function argument is always an *assignment* (you are _assigning_ a value from a different variable to an argument). If you have a variable declared as type `twoProps` and then try to assign `a` to it, you'll witness the same behaviour. – Ben Wainwright Apr 18 '22 at 17:33
  • 1
    Oh I see thank you very much both of you – sir-haver Apr 18 '22 at 17:35

0 Answers0