I have gotten the next bunch of code.
const func: ( newState: { newState: number }) => void = ({ newState: newState }) => {
console.log(newState);
}
For me, particularly interesting is the ({ newState: newState })
how is it work?
Why can I write newState: newState
in this situation, and no compilation errors?
CodePudding user response:
const func: ( labeledParameter: { newState: number }) => void = ({ newState: test }) => {
console.log(test);
}
func({newState: 12});
It's because the first newState is a label put on the parameters give to the function -> i renamed it labeledParameter in my sample
the object
{ newState: newState }
is an object with a property newState and as value a number
to call the function you should use
func({newState: 12});
CodePudding user response:
Let's understand by segregating the typescript and javascript portions in your code snippet.
TypeScript Portion
( newState: { newState: number }) => void
The portion above defines the type of the function which states that the function accepts an argument (which can be named anything, here it's named newState
) that is an object with a key newState
which is of type number
and the void
return type states that the function returns nothing.
JavaScript Portion
({ newState: newState }) => {
console.log(newState);
}
And the portion above is the function definition where the argument is destructed in-place and the newState
key has been aliased to newState
, which is redundant, but works.
A more elaborate version of the above code snippet is as follows:
type Func = (newState: { newState: number }) => void
const func: Func = (arg) => {
const { newState: renamed } = arg;
console.log(renamed);
}
CodePudding user response:
const func: ( labeledParameter: { newState: number }) => void = ({ newState: test }) => { console.log(test); }
func({newState: 12}); It's because the first newState is a label put on the parameters give to the function -> i renamed it labeledParameter in my sample
the object
{ newState: newState } is an object with a property newState and as value a number
to call the function you should use
func({newState: 12});