2

I have a type like this:

type Wrapper<T> = {
    [K in keyof T]: {
        value: T[K];
        meta: string[];
    }
}

I have a function createWrapper that takes an object and creates a wrapper out of it:

const createWrapper = <T extends object>(obj: T): Wrapper<T> => {
    let wrapper: any = {};
    for (let key in obj) {
        wrapper[key] = {
            value: obj[key],
            meta: []
        };
    }
    return wrapper as Wrapper<T>;
}

How could I type the object creation inside createWrapper to avoid any and as Wrapper<T> types?

Thanks a lot for the help!

4
  • Possible duplicate of Typescript empty object for a typed variable Commented Aug 2, 2019 at 10:16
  • @JurajKocan I actually want to avoid type assertions. The question you mentioned provides type assertions as an alternative to null. I want to know if there is a way for TypeScript to detect that every key of T is assigned to the new object and therefore it satisfies the type. Commented Aug 2, 2019 at 10:28
  • this if is the problem? well... interesting, i cant find any ts solution for this Commented Aug 2, 2019 at 10:59
  • If you want your runtime code to stay the same, you pretty much need type assertions. You can make it a bit better by writing let wrapper: Partial<Wrapper<T>> = {} instead of using any. But after the loop the compiler will not understand by itself that all the keys are present. You can make user-defined type guards, but a well-placed assertion is probably your best bet here. Commented Aug 2, 2019 at 22:54

0

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.