typescripttypescript2.2

TypeScripts has no compile time error although wrong type is passed to method


method call:

  this.onChangeScoreGradeType(this.gradingKeyForm.get("scoreGradeType").value.key);

method definition:

onChangeScoreGradeType(scoreGradeType: KeyValue<string,string>) 
{

}

this.gradingKeyForm.get("scoreGradeType").value

is of type KeyValue<string,string>

Why occurs there no compile error, that

this.gradingKeyForm.get("scoreGradeType").value.key

which is a string does not fit into a KeyValue<string,string> instance?

What do I have to change in my TypeScript settings?

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"
    ]
  }
}

Solution

  • In this.gradingKeyForm.get("scoreGradeType").value.key the type is TKey. Generics become any if they cannot be inferred. Hence key is probably of type any which makes it compatible with everything.