Issue
In TypeScript, I can do this:
interface Prop {
prop_a? : number,
prop_b? : string,
prop_c? : string
}
function aa({prop_a, prop_b, prop_c}: Prop) {
console.log('aa: ' + prop_a + ' ' + prop_b + ' ' + prop_c)
}
But then, why this is not allowed:
//A binding pattern parameter cannot be optional in an implementation signature.(2463)
function aaa({prop_a?: number, prop_b?: string, prop_c?: string}) {
console.log('aa: ' + prop_a + ' ' + prop_b + ' ' + prop_c)
}
Also, specifying types of dictionary keys even if they are non-optional (that is removinb ?
from above snippet) is not allowed:
function aaaa({prop_a: number, prop_b: string, prop_c: string}) {
console.log('aa: ' + prop_a + ' ' + prop_b + ' ' + prop_c)
}
Is it just language design choice or its indeed allowed, but am missing something?
Solution
why this is not allowed
Because that's just not how the syntax is defined. You can do it inline, you just replace Prop
with the definition of Prop
:
function aa({prop_a, prop_b, prop_c}: {prop_a?: number; prop_b?: string; prop_c?: string;}) {
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
console.log('aa: ' + prop_a + ' ' + prop_b + ' ' + prop_c)
}
Is it just language design choice...
The types can't go where you showed them because in that location, they look like renamed destructured parameters (prop_a
renamed to number
, etc.; though you wouldn't be allowed to use string
twice as a destructuring target name):
function aaaa({prop_a: number, prop_b: string, prop_c: string2}) {
console.log("number = " + number);
}
aaaa({prop_a: 42});
Also, it's more consistent for them to go in the same place as your original Prop
.
Answered By - T.J. Crowder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.