简体   繁体   English

Lint 嵌套 Typescript 泛型

[英]Lint nested Typescript Generics

I am looking for a way to correctly express my data model with tyepscript definitions.我正在寻找一种使用打字稿定义正确表达我的数据模型的方法。 So far I have the following:到目前为止,我有以下几点:

type Data = Record<string, string>;

interface DataContainer<D extends Data> { 
    id: string;    
    data: D;
}

interface Context {
    dataContainers: DataContainer<any>[];
}

Typescript Playground 打字稿游乐场

A Context stores a set of DataContainers , where each DataContainer is generic over a specific data structure D .一个Context存储一组DataContainers ,其中每个DataContainer在特定数据结构D是通用的。 Now what I want to express is that each of those data structures D should follow a universal type Data .现在我想表达的是,每个数据结构D都应该遵循一个通用类型Data Ie consisting of arbitrary but fixed <string, string> pairs.即由任意但固定的<string, string>对组成。

I really could not find a proper solution for that, the best thing I found was DataContainer<D extends Data> .我真的找不到合适的解决方案,我找到的最好的东西是DataContainer<D extends Data> Do you think that's a good approach?你认为这是一个好方法吗?

At least the following gives my a linting error as desired:至少以下内容会根据需要给出我的 linting 错误:

interface MyData extends Data {
    x: "1",
    y: 2, // Lint error, because not string. (As I want it)
}

So I conclude that when writing <D extends Data> it would also not be allowed for D to have an entry like y: 2 , correct?所以我得出结论,在编写<D extends Data>时,也不允许D有像y: 2这样的条目,对吗?

Now a real problem for me is that the following does not give me a linting error:现在对我来说是真正的问题在于以下给我一个掉毛的错误:

const myContext: Context = {
    dataContainers: [
        {
            id: "123",
            data: {
                x: 1, // This should be marked by the linter
                y: "2", 
                z: {a: 1}, // This also
            }
        }
    ]
}

I am looking for a way to model my definitions such that a linter would mark this as invalid, because there exists no D such that the above would be a valid Context.我正在寻找一种方法来为我的定义建模,以便 linter 将其标记为无效,因为不存在D使得上述内容成为有效的上下文。 Is that possible?那可能吗? Thanks for your help!谢谢你的帮助!

You are close.你很近。 The issue is with DataContainer<any> .问题在于DataContainer<any> Any effectively turns off type checking where it is used. Any 有效地关闭使用它的类型检查。 This means that since data in DataContainer<any> will be of type any , no checks will be done for the property.这意味着由于DataContainer<any> data将是any类型,因此不会对该属性进行检查。 This is regardless of the constraint you put on D这与您对D施加的约束无关

The simple solution is to not use any , use the constraint as the type argument to DataContainer :简单的解决方案是不使用any ,使用约束作为DataContainer的类型参数:


interface Context {
    dataContainers: DataContainer<Data>[];
}

Playground Link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM