简体   繁体   中英

Constrain generic's object property type

Let's assume we have some function which param is string

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

And there's a generic type

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

And function which accepts param of type Relation and performs action

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

Now TypeScript error message is store[storeKey] is not assignable to type string and I understand why. Is there any way to "deprecate" call of the testFunction if T[K] is not a string (no typeguards, only static type checking)?

UPD: T can have not only string properties

Instead of T you should specify more specific type. ie T extends Record<string, string> :

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]);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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