After reading a blog, I came across the statement that T as K
in TypeScript only works when T is subType of K
or K is subType of T
. I am unsure if this is true or not.
When attempting to use as
with properties defined as Record<T,K>
, an error is thrown, as illustrated below.
interface Test {
x: Record<number, number>;
y: number;
}
// This does not match the type Record<number,number>, causing an error
const x1 = {
x: { 1: 1 },
} as Test;
// These examples work without error
const x2 = {
y: 1,
} as Test;
const x3 = {
x: { 1: 1 },
y: 1,
} as Test;
Initially, it seems that this issue arises because { 1: 1 }
does not align with the type Record<number, number>
, suggesting that the subtype check is shallow. However, there is another scenario where it works.
interface SubTest {
x: 1;
y: 1;
}
interface Test2 {
x: SubTest;
y: number;
}
// Despite { x: 1 } not directly matching SubTest, it functions correctly
const x4 = {
x: { x: 1 },
} as Test2;
In this case, {x:1}
also does not exactly match SubTest
, yet the assertion still works. This leads me to believe it might be a specific problem related to Record<T,K>
. Can someone clarify why? Thank you!
To my surprise, I discovered that this example actually works! Now I am truly confused...
interface Test {
x: Record<number, number>;
y: number;
}
const x4 = {
x: { a: 1 },
y: 1,
} as Test;