本文以实战代码为主。
字符串字面值类型允许你指定字符串只能拥有的确切值。例如:
letmyFavoritePet: "狗";我最喜欢的狗如果把myFavoritePet赋予任何其他字符串都会给出一个错误。
此时,可以把这种情况视为特有的类型别名。
把类型别名和联合类型放一起,你就会得到一个类似枚举的行为。如下所示
typeSpecies='猫' | '狗' | '鸟;functionbuyPet(pet:Species,name:string){/*.*/}买宠物(my favorite pet/* ' dog ' asdefinedabove */,' Rocky ');//Argumentoftype""Snake " "是notassignabletoparameterotype“物种”.//buyPet('蛇','叶');
字符串字面类型可以用来区分函数的重载。为了演示这个功能,我们让布衣宠物函数返回一个宠物类型。并为宠物扩展出几种类型,如下所示:
interfacePet {种:种;名称:字符串吃();walk();睡眠();} interfacatextendspet {物种:‘猫’;} interfaceDogextendsPet {物种:‘狗’;} interfaceBirdextendsPet {物种:‘鸟’;sing();}//接口《洛奇》错误地扩展了接口.//属性“物种”的类型不兼容.键入“摇滚”是notassignabletotype " species "//interfaceRockextendsPet {//species : " rock ";//}
然后编写函数的声明实现和重载:
functionbuyPet(pet:Species,name : string): pet;functionbuyPet(pet:'cat ',name : string): cat;功能购买宠物(宠物: '狗,名:串):狗;功能买宠物(宠物:‘鸟’,名字:串):鸟;functionbuyPet(pet:Species,name:string):Pet{n
bsp;if (pet === "cat") { return { species: "cat", name: name, eat: function () { console.log(`${this.name} eats.`); }, walk: function () { console.log(`${this.name} walks.`); }, sleep: function () { console.log(`${this.name} sleeps.`); } } as Cat; } else if (pet === "dog") { return { species: "dog", name: name, eat: function () { console.log(`${this.name} eats.`); }, walk: function () { console.log(`${this.name} walks.`); }, sleep: function () { console.log(`${this.name} sleeps.`); } } as Dog; } else if (pet === "bird") { return { species: "bird", name: name, eat: function () { console.log(`${this.name} eats.`); }, walk: function () { console.log(`${this.name} walks.`); }, sleep: function () { console.log(`${this.name} sleeps.`); }, sing: function () { console.log(`${this.name} sings.`); } } as Bird; } else { throw `Sorry we do not have a ${pet}. Would you like to buy a dog?`; }}接着,我们实现其它相关函数和使用示例:function petIsCat(pet: Pet): pet is Cat { return pet.species === "cat";}function petIsDog(pet: Pet): pet is Dog { return pet.species === "dog";}function petIsBird(pet: Pet): pet is Bird { return pet.species === "bird";}function playWithPet(pet: Pet) { console.log(`Hey ${pet.name}, lets play.`); if (petIsCat(pet)) { // pet is now from type Cat (pet: Cat) pet.eat(); pet.sleep(); // Error: Type '"bird"' is not assignable to type '"cat"'. // pet.species = "bird"; // Error: Property 'sing' does not exist on type 'Cat'. // pet.sing(); } else if (petIsDog(pet)) { // pet is now from type Dog (pet: Dog) pet.eat(); pet.walk(); pet.sleep(); } else if (petIsBird(pet)) { // pet is now from type Bird (pet: Bird) pet.eat(); pet.sing(); pet.sleep(); } else { throw "An unknown pet. Did you buy a rock?"; }}let dog = buyPet(myFavoritePet /* "dog" as defined above */, "Rocky");// dog is from type Dog (dog: Dog)// Error: Argument of type '"rock"' is not assignable to parameter of type "'cat' | "dog" | "bird".// Type '"rock"' is not assignable to type '"bird"'.// buyPet("rock", "Rocky");playWithPet(dog); // Output: Hey Rocky, lets play. // Rocky eats. // Rocky walks. // Rocky sleeps. 至此,我们对字面值类型的综合使用就完成。接下来,我们在控制台利用ts-node插件来运行此文件(strLiteralType.ts)将会得到我们想要的结果。
动起手来练一练吧。拜托朋友们,记得转发分享啊^_^