简体   繁体   中英

Argument of function is a property that exists in a type of Typescript

I want to write a function that returns a single property that exists on a type:

type CustomType = {
    property1: boolean;
    property2: numeric;
};

private getData(obj): CustomType {
    // do stuff
    return dataObj;
}

private getBooleanValue(obj, key): boolean {
    const value = this.getData(obj)[key];
    // do stuff
    return value;
}

I want to put a restriction on getBooleanValue's key, that the key is part of CustomType - for example:

getBooleanValue(obj, "property1") // OK
getBooleanValue(obj, "property2") // ERROR, TypeScript won't allow this

It seems that this kind of works, but it doesn't seem the best solution:

type FilterFlags<Base, Condition> = {
    [Key in keyof Base]: Base[Key] extends Condition ? Key : never;
};

type AllowedNames<Base, Condition> = FilterFlags<Base, Condition>[keyof Base];


private getValue(
    obj, 
    key: keyof AllowedNames<CustomType, boolean>
): boolean {
    const value = this.getData(obj)[key];
    // do stuff
    return value;
}

EDIT: I've found a great article about filtering props in types (conditional types): https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c

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