refrence:
const fn1 = (arg1: {
key: number,
})=>{
console.log(arg1)
}
fn1({
key: 1
})
const data = {
key: 1,
a: 1,
}
fn1(data)
fn1({
key: 1,
a: 1,
})
- link
- who can give some help: Why doesn't ts call the function when declaring a variable, indicating a type error
CodePudding user response:
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. 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)
}
CodePudding user response:
To solve the error
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.
However, you can still make your function generic to make it compiles.
const fn1 = <T extends {key: number}>(arg1: T)=>{
console.log(arg1)
}
Edit
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.
You can turn on suppressImplicitAnyIndexErrors
in your tsconfig if you prefer to ignore it. But it is generally not recommended by typescript.