【问题标题】:Return type based on parameter that is key in an interface基于接口中关键参数的返回类型
【发布时间】:2021-08-10 18:53:38
【问题描述】:

我有如下界面:

interface Elements {
   divContainer: HTMLDivElement;
   inputUpload: HTMLInputElement;
}

那我想做一个这样的函数:

getElement(name: keyof Elements): Elements[name] {
    // Code to get the element.
}

const div = getElement("divContainer"); // returns HTMLDivElement
const input = getElement("inputElement"); // returns HTMLInputElement

但它不起作用,因为我不能将参数用作类型来用作返回类型。我已经玩过Parameters,但似乎无法正常工作。

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    Generics 可以在这里提供帮助:

    getElement<T extends keyof Elements>(name: T): Elements[T];
    

    Playground

    【讨论】:

    • 谢谢!我可以发誓我用这种方法试过但没有用,但显然我做错了。
    【解决方案2】:

    我不能将参数用作返回类型的类型

    所以改用它的类型:

    getElement(name: keyof Elements): Elements[typeof name] {
        // Code to get the element.
    }
    

    【讨论】:

    • 这似乎也可以,虽然我认为它看起来很奇怪,因为 typeof name 在这种情况下只是表示“字符串”......
    • 不完全。由于keyof 产生Elements 键的文字联合,因此名称的类型不仅仅是string,而是(在您的情况下)"divContainer" | "inputUpload"。请注意,您的代码中没有任何内容可以防止 Elements 键成为数字而不是字符串。
    • 你是对的,但在这种情况下,它看起来仍然可以两者兼而有之。根据 Aleksey 的回答,更明显的是,它需要从元素中返回特定输入的名称。无论如何,两者都有效,我只是喜欢其他解决方案看起来更好的方式:)
    • 当然,我也会采用 Aleksey 的解决方案。
    猜你喜欢
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 2022-11-04
    相关资源
    最近更新 更多