将 TypeScript 类型支持与下划线结合使用



我确实想在某些半复杂模型的undescore'where'方法中使用类型检查。例如:

class User {
    public name: string;
    public age: number;
    public someOtherProperty: any;
}

我有称为用户的此类版主列表

现在我想让所有用户名为"John"的用户,下划线方法"where"

public getAllJohns():Array<User> {
    return _.where<User, any>(this.users, {
        name: 'John'
    });
}

这没关系,但是为什么我必须放弃Type Guard?当我不小心写的时候,得到错误真是太好

public getAllJohns():Array<User> {
    return _.where<User, any>(this.users, {
        names: 'John'
    });
}

为第二个"泛型"参数创建接口列表,例如

interface byName {
    name: string;
}

不是解决方案,因为将有许多不同的方法具有不同的所需属性列表来检查。

那么..有没有人对此有一个很好的解决方案,或者它更多的是应该去打字稿团队,比如功能请求。

不幸的是,如果您希望保持类型安全,则确实需要为 where 方法的第二个参数指定一些类型类型。这可以是一个内联接口,但这并不能真正让你得到任何地方。

如果您只关心必须需要给定类型的成员的大量组合,则可以使用具有可选成员的接口:

interface IUser {
    name?: string;
    age?: number;
    someOtherProperty?: any;
}

之后是微不足道的:

public getAllJohns(): Array<User> {
    return _.where<User, IUser>(this.users, {
        names: 'John' // Error: Property 'names' does not exist on type 'IUser'
    });
}

第二个参数是一个对象,其中包含用户界面中定义的一些键,对吗?那么,构建一些具有完全相同的键/类型但可选字段的查询接口是否合适?

class UserCondition {
    public name?: string;
    public age?: number;
    public someOtherProperty?: any;
}

结合严格的对象文字检查(又名新鲜度,https://basarat.gitbooks.io/typescript/content/docs/types/freshness.html),这可以帮助您的查询更加类型安全。

public getAllJohns():Array<User> {
    return _.where<User, UserCondition>(this.users, {
        name: 'John'
    });
}

最新更新