Is there a way to target a simple JavaScript object type in TypeScript?

I am trying to write a function where I would like to indicate that it returns some simple JavaScript object. The signature of the object is unknown and not yet interesting, only the fact that it is a simple object. I mean a simple object that satisfies, for example, jQuery functions isPlainObject. for instance

{ a: 1, b: "b" }

is a simple object but

var obj = new MyClass();

is not a "simple" object, since it is constructornot Object. jQuery does some more precise work in $.isPlainObject, but that is beyond the scope of the question.

If I try to use a type Object, it will be compatible with any custom object, since they are inherited from Object.

Is there a way to set the type of a “simple object” in TypeScript?

, , .

var obj: PlainObject = { a: 1 }; // perfect
var obj2: PlainObject = new MyClass(); // compile-error: not a plain object

, . ASP.NET MVC-.

export class MyController {
  ...
  static GetResult(id: number): JQueryPromise<PlainObject> {
    return $.post("mycontroller/getresult", ...);
  }
  ...
}

, , - .

export class MyViewModelClass {
  ...
  LoadResult(id: number): JQueryPromise<MyControllerResult> { // note the MyControllerResult strong typing here
    return MyController.GetResult(id).then(plainResult => new MyControllerResult(plainResult));
  }
  ...
}

, JQueryPromise<any> JQueryPromise<Object>. , done then. , viewmodel , .

PlainObject, , , PlainObject MyControllerResult, - .

+4
1

- , :

export type PlainObject = { [name: string]: any }
export type PlainObjectOf<T> = { [name: string]: T }

:

export function isPlainObject(obj: any): obj is PlainObject {
    return obj && obj.constructor === Object || false;
}

, , , , , .
, , :

type PlainObject = {
    constructor: ObjectConstructor;
    [name: string]: any
}

, 'lib.d.ts' :

interface Object {
    /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */
    constructor: Function;

    ...
}

:

let o: PlainObject = { key: "value" };

:

Type '{ key: string; }' is not assignable to type 'PlainObject'.
  Types of property 'constructor' are incompatible.
    Type 'Function' is not assignable to type 'ObjectConstructor'.
      Property 'getPrototypeOf' is missing in type 'Function'.
+1

Source: https://habr.com/ru/post/1668757/


All Articles