Typ Guards ist Typoskript - Funktion ermöglicht es Ihnen , innerhalb eines bedingten Block den Typ eines Objekts zu verengen. Es bedeutet , dass Sie Art Ihrer Variable Bedingungen und Schalter angeben können.
Wie es funktioniert?
Lassen Sie uns sagen, dass wir zwei Schnittstellen und ein Objekt:
interface IDog {
woof();
}
interface ICat {
meow();
}
const animal: IDog | ICat = getAnimal();
animal.woof(); // can we do it? ...typescript don't know because animal may be a kitten
Lassen Sie uns einige Funktionen unserer Schnittstellen hinzufügen
interface IDog {
type: "Dog"; // yes, type of type is just a string literal
woof();
}
interface ICat {
type: "Cat";
meow();
}
const animal: IDog | ICat = getAnimal();
switch (animal.type) {
case "Dog":
animal.woof(); // now we are sure that animal has woof because only Dog has this method
return;
case "Cat":
animal.meow(); // typescript understands what type we are using now
return;
default:
throw Error("I don't know given animal");
}
So, jetzt können wir Union-Typen unterscheiden.
Schauen wir uns, wie wir es in unseren Anwendungen verwenden
function someReducer(state: ISomeState = getDefaultSomeState(), action) {
switch (action.type) {
case "FIRST": {
// What is inside action.payload?
return {...};
}
case "SECOND": {
// Does action.payload have a name property?
return {...};
}
default: {
return state;
}
}
}
Wenn Sie viele Aktionstypen haben, können Sie diese Fragen nicht sicher beantworten. So können wir Typoskript helfen uns helfen.
Schauen wir uns Datei erklärt unser Handeln:
interface IFirstAction {
type: "FIRST";
payload: {
name: string;
};
}
interface ISecondAction {
type: "SECOND";
payload: {
age: number;
};
}
// we declare union type here
export type TAction =
IFirstAction |
ISecondAction;
Und unser Minderer:
function someReducer(state: ISomeReducerState = getDefaultSomeState(), action: TAction) {
switch (action.type) {
case "FIRST": {
// What is inside action.payload?
// Even our favourite IDE will tell us that action.payload has a name property
// And the name is a string
return {...};
}
case "SECOND": {
// Does action.payload have a name property?
// Nope, action.payload has an age property only
return {...};
}
default: {
return state;
}
}
}
Nun, wenn Sie Typoskript und redux entwickeln, verwenden Sie Typ Guards zu. Es wird auf jeden Fall Zeit für Sie und Ihr Team speichern.
Sie können auch über andere lesen erweiterte Typoskript Funktionen