I can't seem to wrap my head around why TypeScript is behaving in the way described below.
Snippet
01| const dictionary: { [key: string]: unknown} = {}
02|
03| function set<T>(key: string, value: T): void {
04| dictionary[key] = value;
05| }
06|
07| function get<T = unknown>(key: string): T {
08| return dictionary[key] as T;
09| }
10|
11| set('foo', 'bar');
12|
13| const a: string = get('foo');
14|
15| const _b = get('foo');
16| const b: string = _b;
Behavior
TS throws an error on Line 16 but not Line 13.
Expectation
Considering that the generic type T
of the get
function defaults to unknown
, I expected both Line 13 and Line 16 to trigger TS errors since unknown
shouldn't be able to be assigned to a variable of type string
. Surprisingly, it doesn't flag Line 13, and when I hover over the get
function on Line 13, it shows the return value as a string
instead of unknown
.
I've spent hours trying to make sense of this behavior. Any assistance would be greatly appreciated.
Furthermore, as a follow up question, what modifications should I implement to prompt TypeScript to raise errors on both lines?
EDIT
Apologies for any confusion. I actually INTEND for TypeScript to throw errors on both Line 13 & Line 16, pushing me to specify the generic type string
. In other words, I want it to require me to use get<string>('foo')