typescript - Is it possible to get exact type from object property depends on values? - Stack Overflow

Example:type User = {id: numbername: string}const user: { fields: (keyof User)[] } = {fields: ["

Example:

type User = {
    id: number
    name: string
}

const user: { fields: (keyof User)[] } = {
    fields: ["name"]
}

type result = Pick<User, (typeof user.fields)[number]>

Result contains all User fields, but I need only "name"

It is possible if move fields outside, but I want to keep type safety.

Example:

type User = {
    id: number
    name: string
}

const user: { fields: (keyof User)[] } = {
    fields: ["name"]
}

type result = Pick<User, (typeof user.fields)[number]>

Result contains all User fields, but I need only "name"

It is possible if move fields outside, but I want to keep type safety.

Share Improve this question edited Mar 6 at 14:52 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Mar 6 at 14:51 Pavel PetrovPavel Petrov 113 bronze badges 1
  • You explicitly said that user.fields is an array of any keyof User. You want a narrower type, e.g. tsplay.dev/m34ybW. – jonrsharpe Commented Mar 6 at 14:53
Add a comment  | 

2 Answers 2

Reset to default -1

Annotating a variable means assigning the annotation's type to it, so it would key keyof User. To preserve an exact narrow type use satisfies keyword:

Playground

const user = {
    fields: ["name"]
} satisfies { fields: (keyof User)[] } ;

Yes, you can achieve this using as const to preserve the literal type of fields:

const user = { fields: ["name"] as const };

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744968232a4603814.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信