最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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 };
发布评论

评论列表(0)

  1. 暂无评论