2017-02-20 4 views
0

Warum verhält sich der Code wie folgt? Ist es ein Fehler im TypeScript-Compiler oder fehlendes Feature?Teilweise <T> funktioniert nur mit Inline-Werten

class MyType { 
    constructor(public readonly value1: string, public readonly value2: number) { 
    } 
} 

function myFunction(props: Partial<MyType>): void { 
    // Do something here  
} 

myFunction({ }); // Compiles 
myFunction({ value1: 'string', value2: 42 }); // Compiles 
myFunction({ wrongValue: true }); // Compile error!! 

const myValue1 = {}; 
const myValue2 = { value1: 'string', value2: 42 }; 
const myValue3 = { wrongValue: true }; 

myFunction(myValue1); // Compiles 
myFunction(myValue2); // Compiles 
myFunction(myValue3); // Compiles, but why?!? I expected this not to compile! 

I verwendet Typoskript Version 2.1.6

Antwort

1

Was Sie fordern genaue Typ ist, der here verfolgt wird.

Gegenwärtig prüft TypeScript nur übermäßige Objektschlüssel für Objektliteral, hauptsächlich für Tippfehler. Nachdem Sie ein Objekt an eine Variable gebunden haben, überprüft TypeScript keine übermäßigen Schlüssel.

Spec: https://github.com/Microsoft/TypeScript/blob/02547fe664a1b5d1f07ea459f054c34e356d3746/doc/spec.md#3115-excess-properties

Teil ist optional Markierung auf die Felder der Klasse effektiv hinzuzufügen.

So meldet es keinen Fehler für myValue3.

Verwandte Themen