I have started learning typescript and came across defining the type of an argument in a different way than usual.
function postThread({userId}:{userId:string}) {
// code to be executed
}
instead of this
function postThread({userId}:string) {
// code to be executed
}
why can’t we directly assign the type to it?
3
Answers
Let’s break down the differences:
In this case, you’re using object destructuring in the function parameter. The function postThread expects a single argument, which should be an object with a property named
userId
of type string.In this version, you’re directly specifying that the function expects a single argument of type string. This is not using object destructuring, but rather just declaring the expected type of the parameter. However, this seems to be incorrect, as you’re trying to destructure an object, but the provided type is just string.
In your first example you explicitly add a type to your object parameter which is destructured immediately .
Your second example produces a compiler error. Again, you destructure a property
userId
of an object parameter which has a explicit type ofstring
. However, a primitivestring
does not have a propertyuserId
.Unless you actually defined
userId
on theString
interface:TypeScript Playground
This declares an object type
{ userId: string }
, and destructures theuserId
property from the parameter with that object type.Note how when you call the function, you pass it an object with a
userId
property.This is basically equivalent to:
This is not valid.
{ userId }: string
attempts to access theuserId
property of a string, which won’t work. This will raise a type error.A common alternative, and what your second snippet probably meant to show, is this:
In this example, the function accepts a simple
string
parameter.Note how when you call the function, you pass it a string, and not an object.