born2net born2net - 3 months ago 7
TypeScript Question

In TypeScript, object returns union of two types and yet an error is generated

In TypeScript, object returns union of two types and yet an error is generated .

Here is the main method:

```
public getSelected(): ISimpleListItem | { [key: string]: ISimpleListItem } {
if (this.multiSelect) // true of false
return this.m_metadata; // metadata is when MANY ISimpleListItem returned

// single ISimpleItem returned
for (let v in this.m_metadata) {
if (this.m_metadata[v].selected == true)
return this.m_metadata[v];
}
}


```

notice that it can return both a single ISimpleListItem as well as an object literal holding MANY ISimpleListItem(s)

The interface:
```
export interface ISimpleListItem {
item: any,
index: number,
selected: boolean
}

```

The method that uses simpleList.getSelected() in this case will receice just a single ISimpleList item


private onSelecting(event) {
var orderSelected:ISimpleListItem = this.simpleList.getSelected();
this.selectedAdnetPackageModel = orderSelected.item;
}


and yet the error persists of:

enter image description here

Answer

If I understand you right then:

let myObject: { [key: string]: ISimpleListItem } = {
    "key1": {
        index: 1,
        item: "something",
        selected: true
    }
};

(code in playground)