0

How to pick properties from deep object? It seems T[key]['default'] is not allowed in Mapped type?

type MyModule = {
  title: {
    default: string
  },
  length: {
    default: number
  }
}

// expected type
type NewMyModule = {
  dataModel: string; // type of 'default' prop
  length: number; // type of 'default' prop
}


// error message: 'default' can't be used to index type 'T[key]'

type PickDefault<T> = {
  [key in keyof T]: T[key]['default']
}

1 Answer 1

2

The reason why Typescript yells at you is that it doesn't know whether or not the key default exists on type T[key]. There are two approaches you could take to resolve this issue. The first one is to constraint the input type parameter T that Typescript would know what the type of T[key] is. See below.

type PickDefault<T extends Record<keyof any, { default: unknown }>> = {
  [key in keyof T]: T[key]['default'];
}

Something else you could do is to use type inference. See below.

type PickDefault2<T> = {
  [key in keyof T]: T[key] extends { default: infer D } ? D : never;
}

A caveat for the second approach is that if default is not found on T[key], it will not raise any errors. Instead, it will just replace the type with never. Whereas the first approach will only allow appropriate types to pass.

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.