function postThread({ userId }: { userId: string }) {
console.log(userId) // outputs a string
}
postThread({ userId: 'abc123' })
This code snippet defines an object type { userId: string }
, and extracts the userId
property from the parameter using destructuring.
When calling the function, an object with a userId
property is passed as an argument.
The equivalent way to write this functionality would be:
function postThread(props: { userId: string }) {
const userId = props.userId
console.log(userId) // outputs a string
}
postThread({ userId: 'abc123' })
function postThread({ userId }: string) {
// will not compile
}
The syntax { userId }: string
is invalid because it tries to access the userId
property of a string, resulting in a type error.
A more common alternative approach, which was probably intended in the second example, is demonstrated here:
function postThread(userId: string) {
console.log(userId) // outputs a string
}
postThread('abc123')
In this case, the function accepts a single string
parameter directly.
When invoking the function, you simply provide a string value, rather than an object.