尽管将错误的类型传递给方法,TypeScript 没有编译时错误
TypeScripts has no compile time error although wrong type is passed to method
方法调用:
this.onChangeScoreGradeType(this.gradingKeyForm.get("scoreGradeType").value.key);
方法定义:
onChangeScoreGradeType(scoreGradeType: KeyValue<string,string>)
{
}
this.gradingKeyForm.get("scoreGradeType").value
类型为KeyValue<string,string>
为什么会出现没有编译错误,那
this.gradingKeyForm.get("scoreGradeType").value.key
哪个字符串不适合 KeyValue<string,string>
实例?
我必须在我的 TypeScript 设置中更改什么?
export default class KeyValue<TKey,TValue>
{
constructor(public key: TKey,public value: TValue)
{
}
}
tsconfig.json
{
"compilerOptions": {
"baseUrl": "",
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es6", "dom"],
"mapRoot": "./",
"module": "es6",
"moduleResolution": "node",
"outDir": "../dist/out-tsc",
"sourceMap": true,
"target": "es5",
"typeRoots": [
"../node_modules/@types"
]
}
}
在 this.gradingKeyForm.get("scoreGradeType").value.key
中,类型是 TKey
。如果无法推断泛型,则泛型变为 any
。因此 key
可能是 any
类型,这使得它与所有东西兼容。
方法调用:
this.onChangeScoreGradeType(this.gradingKeyForm.get("scoreGradeType").value.key);
方法定义:
onChangeScoreGradeType(scoreGradeType: KeyValue<string,string>)
{
}
this.gradingKeyForm.get("scoreGradeType").value
类型为KeyValue<string,string>
为什么会出现没有编译错误,那
this.gradingKeyForm.get("scoreGradeType").value.key
哪个字符串不适合 KeyValue<string,string>
实例?
我必须在我的 TypeScript 设置中更改什么?
export default class KeyValue<TKey,TValue>
{
constructor(public key: TKey,public value: TValue)
{
}
}
tsconfig.json
{
"compilerOptions": {
"baseUrl": "",
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es6", "dom"],
"mapRoot": "./",
"module": "es6",
"moduleResolution": "node",
"outDir": "../dist/out-tsc",
"sourceMap": true,
"target": "es5",
"typeRoots": [
"../node_modules/@types"
]
}
}
在 this.gradingKeyForm.get("scoreGradeType").value.key
中,类型是 TKey
。如果无法推断泛型,则泛型变为 any
。因此 key
可能是 any
类型,这使得它与所有东西兼容。