Home > Blockchain >  Typescript: Why does `as unknown as x` work
Typescript: Why does `as unknown as x` work

Time:10-02

I have data its type is ItemDTO. I want to pass it into a function that accepts an argument of type Item.

Typescript is complaining that this might be a mistake because the two types do not sufficiently overlap and if it's intentional to convert to unknown first.

Why does this work? What is it about converting a type to unknown first that works?

Said another way:

function foo(arg: Item){}
const data: ItemDTO = {key: 123}
const results = foo(data as Item) // this doesn't work
const alternative = foo((data as unknown) as Item) // this works

CodePudding user response:

Basics

A as B works if A can be assigned to B OR B can be assigned to A.

Your case

data as Item will only work if data can be assigned to Item OR Item can be assigned to data. Since this is not true data as Item is an error.

data as unknown works because anything can be assigned to unknown and therefore data can be assigned to unknown. => 1

unknown as Item works because again anything can be assigned to unknown and therefore Item can be assigned to unknown. => 2

data as unknown as Item works because 1 && 2 are allowed.

More

This is known as double assertion.

References

  • Related