0

I have a Props type that looks as follows

type Props<FormData> = {
    formData: FormData,
    sectionNme: keyof FormData,
    name: string
}

but what I'd like is something akin to

type Props<FormData> = {
    formData: FormData,
    sectionNme: keyof FormData,
    name: keyof FormData[sectionName]
}

but I can't seem to access the sectionName field in this type definition. Is there a better way to type this, other than just string?

1
  • Could you give an example object how it should look like? Commented Jul 13, 2020 at 12:51

1 Answer 1

1

Introduce a second type parameter:

type Props<FormData extends object, K extends keyof FormData = keyof FormData> = {
    formData: FormData,
    sectionNme: K,
    name: keyof FormData[K]
}

Usage:

interface MyForm {
    foo: {
        bar: string;
    }
}

const props: Props<MyForm> = {
    formData: {
        foo: {
            bar: 'hello'
        }
    },
    sectionNme: 'foo',
    name: 'bar',
}
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.