Lately, I've been delving into TypeScript and encountered a puzzling issue. To illustrate the problem, I have crafted an example as shown below:
type Options<T> = {
props: T;
g: (x: T) => void;
};
function f<T>(options: Options<T>) {
console.log(options);
}
// Example 1 (expected type for x and props)
f({
props: {
foo: {
a: 200,
bar: () => {}
}
},
g(x) {
// x is of the expected type
console.log(x)
}
});
// Example 2 (unknown types for x and props)
f({
props: {
foo: {
a: 100,
bar: function() {}
}
},
g(x) {
// x's type is unknown
console.log(x)
}
});
In the first example, hovering over props
reveals it has the correct type. However, in the second example, despite minimal changes, props
is labeled as unknown
. Why does this happen? You can explore the examples further on TS Playground.