[英]Typescript: string is assignable to {} Type
Why is this:为什么是这样:
const test: {} = "test" // shouldn't this raise "Type 'string' is not assignable to type '{}'." error?
console.log(test)
A valid Typescript code?有效的 Typescript 代码?
Just a moment ago this bit of code caused me to send wrong API calls, because I had something like this:刚才这段代码导致我发送了错误的 API 调用,因为我有这样的事情:
const getAPIData = async (id: string, filters: NetworkFilters | {} = {})
What I wanted to achieve is the filters
prop to have default value of object with no properties, but by my mistake I passed string there and this broke my API calls.我想要实现的是
filters
道具具有默认值 object 没有属性,但我错误地在那里传递了字符串,这破坏了我的 API 调用。 Why is it possible?为什么有可能? It should raise an error.
它应该引发错误。
This is sadly one of the edge cases in TS where it's probably a good idea to explain what assignable
actually means.可悲的是,这是 TS 中的边缘情况之一,解释
assignable
的实际含义可能是一个好主意。
{}
is an object without properties, but as such, any object is assignable to it and string
is not exception. {}
是一个没有属性的 object,但因此,任何 object 都可以分配给它, string
也不例外。 ( string
also has methods fe toLowerCase
). (
string
也有方法 fe toLowerCase
)。
If you for example declared const test: { toLowerCase: () => string } = "test"
, you will also not get an error, because toLowerCase
is a method of string
.例如,如果你声明
const test: { toLowerCase: () => string } = "test"
,你也不会得到错误,因为toLowerCase
是string
的一个方法。
If you said const test: { notAStringMethod: () => string } = "test"
, then this fails, because notAStringMethod
is not a method of string
and thus isn't assignable.如果您说
const test: { notAStringMethod: () => string } = "test"
,那么这将失败,因为notAStringMethod
不是string
的方法,因此不可分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.