1

How can I use extends on a variable? I want to enforce typing on it, without overriding it's inferred type.

Ideally:

const permissions extends {[K: string]: {guest: boolean, user: boolean, admin: boolean}} = {
    readMessage: {guest: true, user: true, admin: true},
    writeMessage: {guest: false, user: true, admin: true},
    deleteMessage: {guest: false, user: false, admin: true},
};
type Permissions = keyof typeof permissions;
// Permissions = 'readMessage' | 'writeMessage' | 'deleteMessage'

The problem with using a type, is that it's overrides the type inference, so:

const permissions: {[K: string]: {/* ... */}} = {/* ... */};
type Permissions = keyof typeof permissions;
// Permissions = string

The only way I could think of, is wrapping the variable with an empty generic function:

const PermissionExtends = <T extends {[K: string]: {/* ... */}}>(v: T) => v;
const permissions = PermissionExtends({/* ... */});
type Permissions = keyof typeof permissions;
// Permissions = 'readMessage' | 'writeMessage' | 'deleteMessage'

2 Answers 2

2

There is no such feature in typescript unfortunately. Variables either have their type fully inferred based on initializer or the type is specified as a type annotation.

The only way to do it is the function approach you have already discovered.

Sign up to request clarification or add additional context in comments.

Comments

1

Typescript 4.9 introduces the satisfies operator that does exactly this.

Here is the solution for the question with the satisfies operator:

interface Permission {
    guest: boolean;
    user: boolean;
    admin: boolean;
}

const permissions = {
    readMessage: {guest: true, user: true, admin: true},
    writeMessage: {guest: false, user: true, admin: true},
    deleteMessage: {guest: false, user: false, admin: true},
} satisfies Record<string, Permission>;

type Permissions = keyof typeof permissions;
// Permissions = 'readMessage' | 'writeMessage' | 'deleteMessage'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.