首页 > 解决方案 > 在 TypeScript 中扩展接口,其中 module=es6 导致属性不存在

问题描述

当我尝试在 tsconfig.json 中从"module": "commonjs",to切换时"module: "es6",,由于以下错误,我无法再编译以下代码:

models/Combined.ts(12,9): error TS2322: Type '{'name': any; '日期':日期;“职业”:任何;}' 不可分配给类型 'Combined'。
对象字面量只能指定已知属性,而“组合”类型中不存在“名称”。

模型/Combined.ts(22,23):错误 TS2339:“组合”类型上不存在属性“名称”。

模型/组合.ts:

import {
    Simple
} from './';


export interface Combined extends Simple {
    occupation?: string;
}

export function CombinedFromJSON(json: any): Combined {
    return {
        'name': json['Name'],
        'date': !exists(json, 'Date') ? undefined : new Date(json['Date']),
        'occupation': !exists(json, 'Occupation') ? undefined : json['Occupation'],
    };
}

export function CombinedToJSON(value?: Combined): any {
    if (value === undefined) {
        return undefined;
    }
    return {
        'Name': value.name,
        'Occupation': value.occupation,
    };
}

模型/Simple.ts

export interface Simple {
    name: string;
    readonly date?: Date;
}

我已经阅读了一些与此类似的 SO 问题以及 typescript 网站的接口页面,但我仍然在这个问题上摸不着头脑。看起来这应该可以工作,而且当目标模块系统是commonjs. tslint 在开发时完全没有抱怨,我已经尝试过 TS 2.4 和 3.1 都没有运气。

任何帮助/指导将不胜感激!

标签: typescript

解决方案


在这里回答:https ://github.com/Microsoft/TypeScript/issues/28687#issuecomment-442167850

我需要添加"moduleResolution" : "node"到我的 tsconfig.json


推荐阅读