I would like to define type when destructuring an array, But it shows some error:
interface buildTargetProps {
target: string;
path: string;
}
interface buildTargets {
[property: string]: buildTargetProps
};
const ChooseApp: buildTargets = {
'autocomplete': {
target: "test",
path: "./Autocomplete",
},
'search': {
target: "search-root",
path: "./Search",
},
};
let [applicationToBuild] = Object.entries(ChooseApp).find(
([name, props]: [String, buildTargetProps]) => {
if (document.getElementById(props.target)) {
return name;
}
}
);
What I want to do is defined the type of "applicationToBuild" variable, for that I have Tried:
let [applicationToBuild]: [string] | undefined = Object.entries(ChooseApp)
I intentionally skipped the other array element, as I don't need that, But I tried to add that as well, to check if that resolves the error, But that also didn't work.
let [applicationToBuild, otherprops]: [string, buildTargetProps] | undefined = Object.entries(ChooseApp)
But, this throws an error.
Type '[string, buildTargetProps] | undefined' is not assignable to type '[string] | undefined'.
Type '[string, buildTargetProps]' is not assignable to type '[string]'.
Source has 2 element(s) but target allows only 1.ts(2322)
Type '[string] | undefined' is not an array type.ts(2461)
finddoes not return an array, instead a single value. In your case it is astring. So, no need of boxes around[applicationToBuild]. 2. You are not explicitly returning anything ififcondition fails. See this: tsplay.dev/1WG7VWfindreturns an array, although I returned name, it returns an array of key and value when found,['autocomplete', {target: "test",path: "./Autocomplete",}]otherwise undefined. from the array, I want just the key which isautocompleteand want to define that it should be of type string.