#Destructuring variable with never type

27 messages · Page 1 of 1 (latest)

stark lagoon
#

Why it's possible to destructure value with never type? However it's not possible to access the value directly from object:

const value: never = { a: 1 };
value.a; // Property 'a' does not exist on type 'never'.
const { a } = value; // a is type never, doesn't throw error

snow crescent
#

no, it's not possible

#

type never is an impossible type

#

you should never have it inside of your code for one of your variable

snow crescent
#

so that means it doesn't have any attribute, and you can destructure it

#

@stark lagoon

fluid inlet
#

Yeah, I'm not sure there's a real satisfying answer here.

#

In theory you could argue that value.a should be okay - never is essentially supposed to be 'read-only any"... but it's probably just considered more useful to error than to not error.

stark lagoon
#

why it doesn't throw an error then? https://www.typescriptlang.org/play?#code/MYewdgzgLgBAbgQwDYFcCmAuGY1zQJxgF4YBvGAMxBCwEYYBfAbgChFU0A6KkJmAen4wACvhAAHAlACeMAOQ85MACYg0EbCFhoAHgEtoMcDBmT5OPPjmcWoSLHI9GxeMnR9BlajAMnpZiwIAGhU1CDA5WCgACzEAdxgCMXwWFiA

I have an type:
declare function useParams<T extends Record<string, string> = never>(): T;

and I set default type as never, to prevent accessing value from useParams, without adding generic to it, but it's still possible to destructure from the hook:

const { id } = useParams(); // should throw error
const { id } = useParams<{ id: string }>() // should work fine

dense stratusBOT
#

@stark lagoon Here's a shortened URL of your playground link! You can remove the full link from your message.

lukaszb48#1856

Preview:ts const value: never = {foo: 1} value.foo // Property 'foo' does not exist on type 'never'. const {foo} = value // foo is type never, doesn't throw error

tribal wigeon
#

this is a known bug

#

1 workaround would be to use a private symbol as a key

#

then you can't destructure anything from it if you dont provide a generic type argument

young summit
#

feels like you could just avoid the situation altogether. hard to say without seeing your actual use case

tribal wigeon
young summit
#

yeah but foo is type never, not usable anywhere

#

so you won't get the error where you want it, but you will see it

tribal wigeon
#

ideally errors should occur at the source of the problem, not where the problematic result is being used

young summit
#

Well I agree, but personally don't think a workaround is necessary

tribal wigeon
#

¯_(ツ)_/¯

#

their question was just "why doesn't this emit an error"

stark lagoon
dense stratusBOT
#

@stark lagoon Here's a shortened URL of your playground link! You can remove the full link from your message.

lukaszb48#1856

Preview:```ts
declare function useParams<
T extends Record<string, string> = never

(): T

const {id} = useParams()```