Issue
I have this typescript code:
type CreateUserFields = {
username: string;
password: string;
confirmPassword: string;
email: string;
// Other fields...
};
export const connectionInfoStepFieldNames: (keyof CreateUserFields)[] = [
'username',
'password',
'confirmPassword',
] as const
export type ConnectionInfoStepFields = Pick<CreateUserFields, (typeof connectionInfoStepFieldNames)[number]>
The problem is that ConnectionInfoStepFields
is equal to all the fields that were defined In CreateUserFields
, where I want it to only Pick
the fields that I defined inside my connectionInfoStepFieldNames
array.
The cause of this problem is this portion of the code: : (keyof CreateUserFields)[]
when I remove it, the problem goes away, but I want to keep it, so that I keep getting type checking on the connectionInfoStepFieldNames
array while I am writing new strings inside of it, so that I don't go out of the scope of the keys defined in CreateUserFields
I thought this would solve it but it did not work:
export const connectionInfoStepFieldNames: ConnectionInfoStepFields[] = [
'username',
'password',
'confirmPassword',
] as const
It gave me this error:
connectionInfoStepFieldNames' is referenced directly or indirectly in its own type annotation. 2502
In simple words, ConnectionInfoStepFields
should be equal to:
'username' | 'password' | 'confirmPassword'
these are exactly the connectionInfoStepFieldNames
array value
Solution
The satisfies
operator solves this exact problem. You can remove the type annotation and instead do this:
export const connectionInfoStepFieldNames = [
'username',
'password',
'confirmPassword',
] satisfies (keyof CreateUserFields)[];
This let's you use typeof
on connectionInfoStepFieldNames
to get its specific type (i.e., ('username' | 'password' | 'confirmPassword')[]
) as you desired, while the satisfies (keyof CreateUserFields)[]
essentially asks TypeScript if connectionInfoStepFieldNames
actually satisfies (keyof CreateUserFields)[]
. If you add 'hello' to the array, it will generate an error saying "Type '"hello"' is not assignable to type 'keyof CreateUserFields'."
You can read the documentation here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html
Answered By - Nkemdi Anyiam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.