1

Let say i have a structure like this:

type Dict<T = any> = {[key: string]: T}

type AsObject<T extends Dict> = {
  [K in keyof T]: (x: any) => T[K]
}

What i do need is the same structure as an array, but how to capture the type for that specific key in the function?

type AsArray<T extends Dict> = {
  key: keyof T
  fn: (x: any) => T[??] // how to get typeof key from here ?
}[]
3
  • 2
    Record<T> is an existing type that covers what your Dict type does Commented Apr 7, 2019 at 11:15
  • Could you explain better what do you mean by key in function? As a in a key in the object return of that function? as functions unlike objects do not have keys Commented Apr 7, 2019 at 13:43
  • @AliHabibzadeh i ment by key the specific key in the object holding a function (in AsObject) Commented Apr 8, 2019 at 18:58

1 Answer 1

3

If you want to ensure the array items have the corect combination of type and fn, you can, using a mapped type, create a union of al valid possibilities for the array item and then use this to define the array:

type Dict<T = any> = Record<string, T>

type AllPosibilities<T extends Dict> = {
    [K in keyof T]: {
        type: K,
        fn: (x: any) => T[K]
    }
}[keyof T]

type AsArray<T extends Dict> = AllPosibilities<T>[]

let arr : AsArray <{
    "a": string,
    "b": number
}> = [
    { type: "a", fn: (x) => "" }, //ok
    { type: "b", fn: (x) => "" },// err
    { type: "b", fn: (x) => 1 }  //ok
]
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.