【问题标题】:Constrain generic's object property type约束泛型的对象属性类型
【发布时间】:2021-01-30 18:43:27
【问题描述】:

假设我们有一个参数是字符串的函数

const action = (param: string) => {
    return param;
};

还有一个泛型类型

interface Relation<T, K extends keyof T> {
    store: T;
    storeKey: K;
}

接受Relation 类型参数并执行action 的函数

const testFunction = <T, K extends keyof T>({ store, storeKey }: Relation<T, K>) => {
    action(store[storeKey]);
};

现在 TypeScript 错误消息是 store[storeKey] is not assignable to type string,我明白为什么。如果T[K] 不是字符串(没有类型保护,只有静态类型检查),有什么方法可以“弃用”testFunction 的调用?

UPD:T 不仅可以有字符串属性

【问题讨论】:

    标签: typescript types typescript-typings


    【解决方案1】:

    您应该指定更具体的类型,而不是T。即T extends Record&lt;string, string&gt;:

    const action = (param: string) => {
        return param;
    };
    
    interface Relation<T extends Record<string, string>, K extends keyof T> {
        store: T;
        storeKey: K;
    }
    
    const testFunction = <T extends Record<string, string>, K extends keyof T>({ store, storeKey }: Relation<T, K>) => {
        action(store[storeKey]);
    };
    

    【讨论】:

    • 是的,但是如果 T 不仅可以具有字符串属性怎么办?
    • 不幸的是,最后有类型转换。即使函数检查给定的键是否对应于store中的字符串,打字稿仍然不知道。
    • 这是一个更简单的解决方案,但我们丢失了密钥自动完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多