Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return type generics possible? #31

Open
Azarattum opened this issue Mar 17, 2023 · 2 comments
Open

Return type generics possible? #31

Azarattum opened this issue Mar 17, 2023 · 2 comments

Comments

@Azarattum
Copy link

The Idea

I know this is a huge thing to ask, but would it be even theoretically possible to achieve type-safety with the return type? So you can just:

const todos = await sql`SELECT * FROM todos`;

Where sql manages sql connection, executes query and returns a type-safe result based on schema.

Possible Implementation?

So, there are native intrinsic generic implementation in typescript already for string-manipulation stuff like Uppercase:

type Uppercase<S extends string> = intrinsic;

Would it be possible to add more of these intrinsic types via a plugin?.. So we could have something like:

type SQLResult<T extends TemplateStringsArray> = intrinsic;

That we can then use in our sql template function implementation.

@frigus02
Copy link
Owner

As far as I know plugins cannot interfere with type checking. They cannot contribute intrinsic types. So this is not possible today.

That said, TypeScript can do some amazing inference on strings. I wonder if you could combine the sql function with something like this:

type SQL<Statement extends string> =
    Statement extends `SELECT ${infer Column} FROM ${infer Table}` ?
    { column: Column, table: Table } : { error: "Cannot parse SQL query" }

type Foo = SQL<"SELECT name FROM users">;
//   ^? type Foo = { column: "name"; table: "users"; }

Playground link

@Azarattum
Copy link
Author

The problem is that we cannot get a const string type with template literals due to this: microsoft/TypeScript#33304

So, it's not possible to implement purely in TypeScript currently. I was hoping there were some workarounds for plugins...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants