1

I'm trying to create an object with specific keys based on the value of the array.

Here is the code:

type AllowedKeys = "foo" | "bar" | "baz"

interface Options {
    keys: AllowedKeys[]
}

interface AllTypesDeclaration {
    foo: string[];
    baz: object[];
    bar: number[];
}

function createObj(arg: Options): Pick<AllTypesDeclaration, typeof arg.keys[number]> {
    return {}
}

const myObj = createObj({ keys: ['baz'] })

// This should work:
myObj.baz

// This should fail:
myObj.foo
myObj.bar

As you can see I tried to do it using Pick, but that doesn't seem to work.

Demo: here

1 Answer 1

3

You will need generics for that, otherwise the type of keys will not be restricted by the input.

function createObj<T extends AllowedKeys[]>(arg: { keys: T })
    : Pick<AllTypesDeclaration, typeof arg.keys[number]> {
    return {}
}
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.