0

I am new to Typescripts and I searched for more than 30 min to figure a usage of as unknown as but couldn't find an answer. What is the purpose of using as unknown as number in the following line of code?

public maxConnections: number = process.env[Env.MAX_CONNECTIONS] as unknown as number;
user3123690
  • 1,053
  • 5
  • 17
  • 27

2 Answers2

2

This might be a possible explanation, as unknown as is at the end of the article, just not with number.

Dávid Laczkó
  • 1,091
  • 2
  • 6
  • 25
0

as unknow as number is known as a Double Assertion. unknown is compatible with all types (like any) and equally unsafe as as any as, but you're only allowed to operate with the value until a specific type is determined. I don't know (yet) vs I don't care. Linters prefer unknown (with no-explicit-any rule)

Typescript: Why does `as unknown as x` work gives this example:

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.

ofthelit
  • 1,341
  • 14
  • 33