概述
in 关键字
interface Admin {
name: string
privileges: string[]
}
interface Employee {
name: string
startDate: Date
}
type UnKnownEmployee = Employee | Admin
function printEmployeeInformation(emp: UnKnownEmployee) {
console.log("Name: " + emp.name)
if ("privileges" in emp) {
console.log("Privileges:" + emp.privileges.join("、"))
}
if ("startDate" in emp) {
console.log("Start Date:" + emp.startDate)
}
}
const params: Admin = {
name: "amin",
privileges: ["张龙"]
}
const params2: Employee = {
name: "amin",
startDate: new Date()
}
printEmployeeInformation(params)
printEmployeeInformation(params2)
typeof
typeof v === "typename"
// string number boolean symbol
function testTypeof(value: string, type: string | number) {
if (["number", "string"].includes(typeof type)) {
console.log(typeof type)
if (typeof type === "number") {
return new Array(type + 1).join("-") + value
}
return type + value
}
console.log("err")
}
instanceof
console.log(padder instanceof SpaceRepeatingPadder) // true false
interface Padder {
getPaddingString(): string
}
class SpaceRepeatingPadder implements Padder {
constructor(private numSpaces: number) {}
getPaddingString(): string {
return Array(this.numSpaces + 1).join("-")
}
}
class StringPadder implements Padder{
constructor(private value: string) {}
getPaddingString(): string {
return this.value
}
}
let padder: Padder = new SpaceRepeatingPadder(6)
let padder2: Padder = new StringPadder("amin")
if (padder instanceof SpaceRepeatingPadder) {
console.log(padder.getPaddingString())
}
if (padder2 instanceof StringPadder) {
console.log(padder2.getPaddingString())
}
自定义类型保护的类型谓词
function isNumber(x: any): x is number {
return typeof x === "number"
}
function isString(x: any): x is string {
return typeof x === "string"
}
console.log(isNumber("amin")) // false
console.log(isNumber(5)) // true
console.log(isString(5)) // false
console.log(isString("amin")) // true
最后
以上就是冷酷薯片为你收集整理的Typescript学习 类型守卫的全部内容,希望文章能够帮你解决Typescript学习 类型守卫所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复