Wenn Sie eine Schnittstelle wie:
interface ISimpleObject {
foo: string;
bar?: any;
}
Diese Schnittstelle nur bei der Kompilierung und für Code-Hinting/intellisense verwendet wird. Schnittstellen werden verwendet, um eine strenge und typensichere Methode zur konsistenten Verwendung eines Objekts mit einer definierten Signatur bereitzustellen.
Wenn Sie eine Funktion mit der interface
oben definiert:
function start(config: ISimpleObject):void {
}
Typoskript Kompilierung schlägt fehl, wenn ein Objekt nicht die genaue Signatur der ISimpleObject
Schnittstelle verfügt.
Es gibt mehr gültigen Techniken für den Aufruf die Funktion start
:
// matches the interface as there is a foo property
start({foo: 'hello'});
// Type assertion -- intellisense will "know" that this is an ISimpleObject
// but it's not necessary as shown above to assert the type
var x = <ISimpleObject> { foo: 'hello' };
start(x);
// the type was inferred by declaration of variable type
var x : ISimpleObject = { foo: 'hello' };
start(x);
// the signature matches ... intellisense won't treat the variable x
// as anything but an object with a property of foo.
var x = { foo: 'hello' };
start(x);
// and a class option:
class Simple implements ISimpleObject {
constructor (public foo: string, public bar?: any) {
// automatically creates properties for foo and bar
}
}
start(new Simple("hello"));
Jedes Mal, wenn die Signatur nicht übereinstimmt, wird die Kompilierung fehlschlagen:
// compile fail
var bad = { foobar: 'bad' };
start(bad);
// compile fail
var bad: ISimpleObject = { foobar: 'bad' };
// and so on.
Es gibt keinen „richtigen“ Weg es zu tun. Es ist eine Frage der Stilwahl.Wenn es ein Objekt ist, das konstruiert wurde (und nicht nur direkt als Parameter übergeben), würde ich normalerweise die Art erklären:
var config: ISimpleObject = { foo: 'hello' };
Auf diese Weise Code-Completion/IntelliSense überall arbeitet ich die config
Variable verwendet:
config.bar = { extra: '2014' };
In TypeScript gibt es kein "Casting". Es wird eine Typ-Assertion genannt und sollte in den hier beschriebenen Fällen nicht benötigt werden (ich habe oben ein Beispiel eingefügt, wo es verwendet werden könnte). Sie müssen die Variable Type nicht deklarieren und dann in diesem Fall eine Assertion verwenden (da der Typ bereits bekannt war).
Ich wünschte, ich hätte mehr Upvotes! – mentat