Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

typescript-- How do you type generics? #382

Answered by Minigugus
RyanDurk asked this question in Q&A
Discussion options

I wrote some example code below with the issue. Basically the table has an id, an "inner" jsonb column and a "type" column.

The error is on the very last line. My workaround is just suffixing an "as T[]" Is there a better way?

import sql from "./server/db"
type MyType = "child" | "other"
interface Parent {
 id: number
 inner: object
 type: MyType
}
interface Child extends Parent {
 type: "child"
 inner: {
 name: string
 }
}
async function run1(): Promise<Child[]> {
 const x = await sql<Child[]>`select id, inner from table`
 return x
}
run1()
async function run2<T extends Parent>(type: MyType): Promise<T[]> {
 const x = await sql<T[]>`select id, inner from table where type = ${type}`
 return x
}

gives this error:

 The types returned by 'pop()' are incompatible between these types.
 Type 'TransformRow<T> | undefined' is not assignable to type 'T | undefined'.
 Type 'TransformRow<T>' is not assignable to type 'T | undefined'.
 Type 'T | { '?column?': T; }' is not assignable to type 'T | undefined'.
 Type '{ '?column?': T; }' is not assignable to type 'T'.
 'T' could be instantiated with an arbitrary type which could be unrelated to '{ '?column?': T; }'.ts(2322)```
You must be logged in to vote

Short answer: indeed, it's a bug... 😞

Long answer: historically, if was possible to pass types like number as row type, and these would be become { '?column?': T }, as postgresql does with unamed columns (like in SELECT 42;). But it was too painful and not really used so contraints on T where added, to enforce objects only (see types), then transforming to '?column?' isn't even possible anymore, so that part should have been removed, to avoid bugs like in your case 😅

A fix is on the way: #383

Replies: 1 comment

Comment options

Short answer: indeed, it's a bug... 😞

Long answer: historically, if was possible to pass types like number as row type, and these would be become { '?column?': T }, as postgresql does with unamed columns (like in SELECT 42;). But it was too painful and not really used so contraints on T where added, to enforce objects only (see types), then transforming to '?column?' isn't even possible anymore, so that part should have been removed, to avoid bugs like in your case 😅

A fix is on the way: #383

You must be logged in to vote
0 replies
Answer selected by RyanDurk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /