TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Can't do a type assertion on an empty array with a branded type.

Open JeanMeche opened this issue 2 years ago • 2 comments

Bug Report

🔎 Search Terms

  • type assertion
  • branded type
  • empty array

🕗 Version & Regression Information

Every version.

⏯ Playground Link

Playground link with relevant code

💻 Code

export type Foo = number & {__brand__: 'foo'};
const a = 3 as Foo; // OK 

export type Bar =  Array<number|string> &{ __brand__: 'bar'; }
const createOpCodes = [] as Bar; // KO 

🙁 Actual behavior

const createOpCodes = [] as Bar; throws :

Conversion of type 'never[]' to type 'Bar' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

🙂 Expected behavior

Should work fine without having to resort to a intermediate assertion like const createOpCodes = [] as unknown[] as Bar;

JeanMeche avatar May 01 '23 18:05 JeanMeche

This follows pretty directly from the rules about which assertions are and aren't allowed. Is there something different about this case in particular, or are you just saying all assertions should always be allowed?

RyanCavanaugh avatar May 02 '23 17:05 RyanCavanaugh

@RyanCavanaugh Perhaps if [] is being asserted, it should have the contextual type of unknown[] instead of never[] to allow it to be downcasted to a branded type?

Josh-Cena avatar May 03 '23 06:05 Josh-Cena

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

typescript-bot avatar May 12 '23 20:05 typescript-bot