'Specifying type of argument dictionary keys in function definition itself
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 1:[1]
That's incorrect syntax, the proper way to do it is this:
function aaa({ prop_a, prop_b, prop_c }: { prop_a?: number, prop_b?: string, prop_c?: string }) {
This is incorrect because the type annotations are inside the destructuring assignment.
function aaa({prop_a?: number, prop_b?: string, prop_c?: string}) {
It is similar to:
const [foo: number, bar: string] = baz; // ! error
const [foo, bar]: [number, string] = baz; // good
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hittingonme |
