Declare variable type after initial declaration typescript

Viewed 3484

I've got the following code:

let item = object[] | object;
if (a === true) {
    item = [];
    // would like to do something like item: object[] = []
    (item as object[]).push(...);
else if (b === true) {
    item = {};
    // would like to do something like item: object = {}
    (item as any).prop = ...
}
// do stuff with item

My problem is that because item can be either an object or a list of objects, I then have to cast item in order for typescript to allow me to work with it. Is there any way to declare the type of object on its initialization, so these casts are unnecessary?


Just to clarify, I DO want item to be typed, I just want that typing to be specified after it is defined.

3 Answers

You could use Type Assertion, like this:

let item: Any 
if ( some condition ) {
let mynewtype = (item as string)
// use mynewtype as string }
Related