functionexample(foo: any) { if (isString(foo)) { // TS2551: Property 'toFixed' does not exist on type 'string'. console.log(foo.toFixed(2)); // 编译期报错 } }
类型谓词的语法规则
类型谓词要写在函数的返回值上,形式为:value is Type,其中value是函数的参数,Type是要判断的类型,比如一个判断number类型的函数可以这样写:
1 2 3
functionisNumber(value: unknown): value is number { returntypeof value === 'number'; }
functionprintProperties(person: Person) { for (const property in person) { console.log(`${property}: ${person[property]}`); } }
printProperties(person);
但是这段代码却报错了:
1
TS7053: Element implicitly has an 'any'type because expression of type'string' can't be used to index type 'Person'. No index signature with a parameter of type 'string' was found on type 'Person'.
眼力好的同学可能已经发现了,上面这个写法可以简化一下,property as keyof typeof person可以简化为property as keyof Person,因为person的类型就是Person,所以我们可以直接使用Person类型来代替。这样可以节省一个typeof操作符的使用。