#How to define an argument where only one property needs to match?

1 messages · Page 1 of 1 (latest)

steep shell
#

This example complains for the second method call because the arg I'm passing also has a b property. How can I define the type for the function argument so that it accepts either method call?

pastel geyserBOT
#
claudekennilol#0

Preview:```ts
const foo = (arg: {f: string}) => {}

foo({f: ""})
foo({f: "", b: ""})```

distant silo
#

There is nothing wrong with the function. It is TS Excess Property Checks

pastel geyserBOT
#
sandiford#0

Preview:```ts
const foo = (arg: {f: string}) => {}

const one = {f: ""}
const two = {f: "", b: ""}

foo(one)
foo(two)```

distant silo
#

all works

#

!hb excess

#

!hb excess property checks

steep shell
#

Do you just mean "any of the following listed here"?

distant silo
#

Check my playground link

#

I mean that your object types work with your function.

steep shell
#

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?

distant silo
#

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

pastel geyserBOT
#
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
distant silo
#

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

steep shell
#

!solved

distant silo
#

There is no error for missing an optional

pastel geyserBOT
#
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'?