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

前端 未结 3 1055
梦谈多话
梦谈多话 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:15

    Tested in TypeScript 3.7.2:

    For a flat plain object, you can do:

    type Primitive =
      | bigint
      | boolean
      | null
      | number
      | string
      | symbol
      | undefined;
    
    type PlainObject = Record;
    
    class MyClass {
      //
    }
    
    const obj1: PlainObject = { a: 1 }; // Works
    const obj2: PlainObject = new MyClass(); // Error
    

    For a nested plain object:

    type Primitive =
      | bigint
      | boolean
      | null
      | number
      | string
      | symbol
      | undefined;
    
    type JSONValue = Primitive | JSONObject | JSONArray;
    
    interface JSONObject {
      [key: string]: JSONValue;
    }
    
    interface JSONArray extends Array { }
    
    const obj3: JSONObject = { a: 1 }; // Works
    const obj4: JSONObject = new MyClass(); // Error
    
    const obj5: JSONObject = { a: { b: 1 } }; // Works
    const obj6: JSONObject = { a: { b: { c: 1 } } }; // Works
    const obj7: JSONObject = { a: { b: { c: { d: 1 } } } }; // Works
    

    Code is an adaptation from https://github.com/microsoft/TypeScript/issues/3496#issuecomment-128553540

提交回复
热议问题