“MappingService”类型中的属性“validate”不能分配给基类型“IMappingService”typescript 2.8.0中的相同属性

时间:2018-02-27 13:21:29

标签: typescript

我正在使用angularjs(1.5.8)框架和最新的打字稿(2.8.0)文件。更新到最新的打字稿版本后,不会编译以下代码。

IMappingService接口:

export interface IMappingService {

/**
 * validation of the mapping of a T object from one type to another object type and return
 *  that new mapped object type
 * @param obj The object to validate
 * @param type The type of the object
 * @returns {T} The new validated and mapped object 
 */
validate<T>(obj: any, type: string, fields: string): T;    
}

接口的实现:

export default class MappingService implements IMappingService {

    public validate<T>(obj: any, type: string, fields: string): T | T[] {
    let parsedFields = null;

    const replacedFields = fields.replace(/'/g, '"');
    parsedFields = JSON.parse(replacedFields);

    let tempobject = obj;

    if (obj instanceof Array) {
        tempobject = obj[0];
        if (!tempobject) {
            return [];
        }
    }
    ....
    return obj;
}

我收到以下错误:

 Property 'validate' in type 'MappingService' is not assignable to the same property in base type 'IMappingService'.
Type '<T>(obj: any, type: string, fields: string) => T | T[]' is not assignable to type '<T>(obj: any, type: string, fields: string) => T'

1 个答案:

答案 0 :(得分:1)

代码在2.7中也不起作用。不知道在哪个版本的Typescript中有效,但它不应该真正起作用,因为它不是类型安全的。请考虑以下事项:

let m : IMappingService = new MappingService();
let r = m.validate<{ name: string }>({}, "", "");
r.name // I can access name, even though the type may be an array since MappingService returns T | T[]

您可以为数组添加重载,也可以将接口更改为与实现相同的签名:

export default class MappingService implements IMappingService {

    public validate<T>(obj: any[], type: string, fields: string): T[]
    public validate<T>(obj: any, type: string, fields: string): T
    // Implementation signature
    public validate<T>(obj: any, type: string, fields: string): T | T[] { ... }
}

let m = new MappingService();
let r = m.validate<{ name: string }>({}, "", "");  // r will be an item 
var rr = m.validate<{ name: string }>([], "", ""); // rr will be an array