0

I'm trying to dynamically change object property values based on the property type, e.g., replace all object string properties with "***". I keep getting Type '"***"' is not assignable to type 'T[keyof T]'

I've tried finding the correct way of doing this in Typescript GitHub repository but no luck.

I'm using the latest version of Typescript as of writing this "3.8.2".

Anyone knows what is the correct way of changing object property values when accessing properties dynamically?

Example:

interface IClassA {
    name: string;
    age: number;
}

const user: IClassA = {
    name: "Jhon Doe",
    age: 20
};

obfuscate(user);

export function obfuscate<T extends IClassA>(obj: T) {
    for (const prop of Reflect.ownKeys(obj) as (keyof T)[]) {
        if (typeof obj[prop] === "string") {
            obj[prop] = "***";
        }
    }
}

enter image description here

2

1 Answer 1

1

I don't know why doing this but the simplest (dirty) hack to do this is casting you text to any :

if (typeof obj[prop] === "string") {
            obj[prop] = ("***" as any);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.