Home > Mobile >  Is there in typescript a common super class for all object like in Java?
Is there in typescript a common super class for all object like in Java?

Time:02-02

I have a method which can return any type of object in my typescript project. In java you would just return Object and then the caller has to cast. How would you do that in Typescript ? Do all classes inherit from a common super class like the Java Object type ??

CodePudding user response:

If you need anything and you will know later what it is, use unknown (you will need to use as type later):

function test(): unknown {
  return { a: 0, b: 1 };
}

test().a // Error
(test() as {a:number,b:number}).a // Ok

If you won't know and care what it is, use any (but this case typesafety goes out of the window):

function test(): any {
  return { a: 0, b: 1 };
}

test().a // Ok

If you know at least it's object, you can type it as object and use Object functions or access it through type guards:

function test(): object {
  return { a: 0, b: 1 };
}

Object.keys(test()) // Ok

// Or use with type guard:

const tst = test()
if ("a" in tst) {
    tst.a // Ok
}

Also see Assignability documentation.

CodePudding user response:

Most of the time the caller will know what to expect. What you can do is to infer the type when calling the function like so:

class A {
  public returnAnyThing<T>(): T {
    return {} as T;
  }
}

interface ReturnValue {
    val: number;
}

class Caller {
    public call(){
        const returnValue = new A().returnAnyThing<ReturnValue>();
        console.log(returnValue.val);
    }
}
  • Related