[英]Why doesn't ts call the function when declaring a variable, indicating a type error
const fn1 = (arg1: {
key: number,
})=>{
console.log(arg1)
}
fn1({
key: 1
})
const data = {
key: 1,
a: 1,
}
fn1(data)
fn1({
key: 1,
a: 1,
})
const fn1 = (arg1: {
key: number,
})=>{
console.log(arg1)
}
here you declare that the parameter should have a key named "key" and a value as a number, nothing more.在这里你声明参数应该有一个名为“key”的键和一个数字值,仅此而已。 if you want to create a type for a parameter that should expect any any key with a number value pair, you need to change it as
如果你想为一个参数创建一个类型,该类型应该期望任何带有数字值对的键,你需要将它更改为
const fn1 = (arg1: {
[k: string]: number
})=>{
console.log(arg1)
}
As the error message suggest:如错误消息所示:
Object literal may only specify known properties, and 'a' does not exist in type '{ key: number; }'
It is the difference between object literal and a named object.它是 object 文字和命名 object 之间的区别。
However, you can still make your function generic to make it compiles.但是,您仍然可以使 function 通用以使其编译。
const fn1 = <T extends {key: number}>(arg1: T)=>{
console.log(arg1)
}
Maybe your question is why, but not how.也许您的问题是为什么,而不是如何。 It is acutally a feature introduced in TypeScript 1.6 to catch programmer human errors on misspelling the property names.
它实际上是TypeScript 1.6 中引入的一个功能,用于捕获程序员在拼写错误属性名称时的人为错误。
You can turn on suppressImplicitAnyIndexErrors
in your tsconfig if you prefer to ignore it.如果您愿意忽略它,可以在 tsconfig 中打开
suppressImplicitAnyIndexErrors
。 But it is generally not recommended by typescript.但是typescript一般不推荐。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.