Skip to content

Dynamic Super Types #11967

Open
Open
@tinganho

Description

@tinganho

Now, that #11929 is PR landed. I would really love to have some syntax to specify an arbitrary super type of T. This can be especially helpful in creating strongly typed ORM database frameworks.

Proposal

If K is constrained to be a key of T i.e K extends keyof T. Then the syntax:

{ ...K: ...T[K] }

Means spread the keys K and values of T in {}.

Example

Here is an example usage of an envisioned ORM framework:

interface IUser {
    id: string;
    name: string;
    email: string;
    createdAt: string;
    updatedAt: string;
    password: string;
    // ...
}

interface Options<T, K extends keyof T> {
     attributes: T[K][];
}

interface Model<IInstance> {
     findOne<K extends keyof IInstance>(options: Options<IInstance, K>): { ...K: ...IInstance[K] };
}

declare namespace DbContext {
   define<T>(): Model<T>;
}

const Users = DbContext.define<IUser>({
   id: { type: DbContext.STRING(50), allowNull: false },
   // ...
});

const user = Users.findOne({
    attributes: ['id', 'email', 'name'],
    where: {
        id: 1,
    }
});

user.id // no error
user.email // no error
user.name // no error

user.password // error 
user.createdAt // error
user.updatedAt // error

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions