Is there any way to target the plain JavaScript object type in TypeScript?

前端 未结 3 1046
梦谈多话
梦谈多话 2021-02-13 09:46

I\'m trying to write a function where I\'d like to indicate that it returns some kind of plain JavaScript object. The object\'s signature is unknown, and not interestin

3条回答
  •  臣服心动
    2021-02-13 10:22

    In my code I have something similiar to what you're asking:

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

    And I also have a type guard for that:

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

    Edit

    Ok, I understand what you're looking for, but unfortunately that is not possible.
    If i understand you correctly then this is what you're after:

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

    The problem is that in 'lib.d.ts' Object is defined like so:

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

    And then this:

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

    Results with an error:

    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'.
    

提交回复
热议问题