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 |2 Answers
Reset to default -1Annotating 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
user.fields
is an array of anykeyof User
. You want a narrower type, e.g. tsplay.dev/m34ybW. – jonrsharpe Commented Mar 6 at 14:53