Skip to content

Typescript: Type-Narrowing Errors #686

Answered by aust1nz
aust1nz asked this question in Q&A
Discussion options

You must be logged in to vote

Doh! I saw the solution in an open issue.

import postgres from 'postgres';

try {
  const result = await sql`select * from users`
} catch (err) {
  if (err instanceof postgres.PostgresError) {
  console.log(err.code) // This is now allowed!
}

I got stumped because if you import the named PostgresError from the package, you wind up with a Typescript type that doesn't work for type narrowing.

import { PostgresError } from 'postgres';

try {
  const result = await sql`select * from users`
} catch (err) {
  if (err instanceof PostgresError) {  // This won't work! PostgresError is a Typescript type.
}

Replies: 1 comment

Comment options

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