Typescript: How I can define strictly constant from type

Viewed 92

I tried to define a type and create a constant from this type. This is what I did:

type  StatusType = 'active' | 'pending';

type Status = Record<Uppercase<StatusType>, Capitalize<StatusType>>;

const UserStatus: Status = {
    ACTIVE: 'Active',
    PENDING: 'Pending'
}

but this also fine if I do something like:

const UserStatus: Status = {
    ACTIVE: 'Active',
    PENDING: 'Active'
}

Is there any way to prevent this? I want the value of the PENDING key to be must be Pending.

1 Answers
type StatusType = 'active' | 'pending';


type Status = {
    [P in StatusType as Uppercase<P>]: Capitalize<P>
}

const UserStatus: Status = {
    ACTIVE: 'Active',
    PENDING: 'Pending'
}

const UserStatus2: Status = {
    ACTIVE: 'Active',
    PENDING: 'Active' // expected error
}

You should use mapped type instead

Related