#How to define an argument where only one property needs to match?
1 messages · Page 1 of 1 (latest)
Preview:```ts
const foo = (arg: {f: string}) => {}
foo({f: ""})
foo({f: "", b: ""})```
There is nothing wrong with the function. It is TS Excess Property Checks
Preview:```ts
const foo = (arg: {f: string}) => {}
const one = {f: ""}
const two = {f: "", b: ""}
foo(one)
foo(two)```
all works
!hb excess
!hb excess property checks
How TypeScript describes the shapes of JavaScript objects.
What do you mean "all works"?
Do you just mean "any of the following listed here"?
Why is it fine (for typescript) to pass a reference to the function, but it complains if the object is passed directly to the function?
TypeScript applies excess property checks when you create an object of a specific type
and when you are creating the object as an argument, it treats the argument type as the type of object you are creating
const o: { a: string } = { a: 'foo', b: 'bar' } as { a: string }
// ^? - const o: {
// a: string;
// }
o.b
// ^
// Property 'b' does not exist on type '{ a: string; }'.
// ^? - any
Because you can never access that b property
It's not technically illegal according to the type system, but TS treats it as an error, to catch likely mistakes
It would be easy to mistype an optional property and not get the object you wanted otherwise
Fair, but I'd expect a different error if it's missing a property that the calling function explicitly expects. I knew that it was valid js (excluding the inline typing in the function arg declaration) but I wasn't sure exactly what ts's problem with it was.
!solved
That's why I said an optional property
There is no error for missing an optional
const foo = (arg: { One: string, Two?: string }) => {}
// incorrect casing
foo({ One: "", two: "" });
// ^^^
// Object literal may only specify known properties, but 'two' does not exist in type '{ One: string; Two?: string | undefined; }'. Did you mean to write 'Two'?