Interface type check with Typescript

前端 未结 17 983
灰色年华
灰色年华 2020-11-22 14:09

This question is the direct analogon to Class type check with TypeScript

I need to find out at runtime if a variable of type any implements an interface. Here\'s my

17条回答
  •  隐瞒了意图╮
    2020-11-22 14:33

    export interface ConfSteps {
        group: string;
        key: string;
        steps: string[];
    }
    
    private verify(): void {
        const obj = `{
          "group": "group",
          "key": "key",
          "steps": [],
          "stepsPlus": []
        } `;
        if (this.implementsObject(obj, ['group', 'key', 'steps'])) {
          console.log(`Implements ConfSteps: ${obj}`);
        }
      }
    
    private objProperties: Array = [];
    
    private implementsObject(obj: any, keys: (keyof T)[]): boolean {
        JSON.parse(JSON.stringify(obj), (key, value) => {
          this.objProperties.push(key);
        });
        for (const key of keys) {
          if (!this.objProperties.includes(key.toString())) {
            return false;
          }
        }
        this.objProperties = null;
        return true;
      }
    

提交回复
热议问题