gpt4 book ai didi

typescript :意外未知

转载 作者:行者123 更新时间:2023-12-03 17:06:07 25 4
gpt4 key购买 nike

我最近一直在使用 TypeScript,偶然发现了一个让我感到困惑的问题。我已将问题放入一个示例中,如下所示:

type Options<T> = {
props: T;
g: (x: T) => void;
};

function f<T>(options: Options<T>) {
console.log(options);
}

// Example 1 (x and props expected type)
f({
props: {
foo: {
a: 200,
bar: () => {}
}
},
g(x) {
// x is the expected type
console.log(x)
}
});

// Example 2 (x and props unknown)
f({
props: {
foo: {
a: 100,
bar: function() {}
}
},
g(x) {
// x is unknown
console.log(x)
}
});
悬停在 props 上时在第一个示例中,您将看到它具有预期的类型。尽管在第二个示例中几乎没有任何变化 props类型为 unknown .这是为什么?这是上面 TS Playground 中的示例.

最佳答案

这是 TypeScript 的设计限制;见 microsoft/TypeScript#38845 .显然(来自 this comment ):

An arrow function with no parameters is not context sensitive, but a function expression with no parameters is context sensitive because of the implicit this parameter. Anything that is context sensitive is excluded from the first phase of type inference, which is the phase that determines the types we'll use for contextually typed parameters.


看起来像是 T 的推断当 foo.bar 成功时属性是一个箭头函数,因为没有上下文 this担心。因此上下文类型成功分配给 x g 的参数,一切都会如你所愿。但是当 foo.bar的值是一个函数表达式,编译器需要上下文来弄清楚是什么 this是,和 T无法及时推断出 g 的上下文类型的参数,它最终变成 unknown .

关于 typescript :意外未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64403067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com