我想使用“is”缩小属性的类型。
class Person{
name:string|undefined;
//I want the return type to be as follows:
hasName()// :this.name is string
{
return this.name!=undefined && this.name !=="";
}
}
const me=new Person();
if (me.hasName()) {
//This has an error.
//'me.name' is possibly 'undefined'.
console.log(me.name.includes("a"));
}
但我不知道这是否可能。 我检查了文档,我发现的唯一示例是缩小参数类型。
您可以像这样使用它,但是空字符串或非空字符串没有特定的类型,因此您可以使用一些品牌类型:
declare const nonEmptyString: unique symbol
type NonEmptyString = string & { [nonEmptyString]: true }
class Person{
name:string|undefined;
hasName(): this is {name: NonEmptyString}
{
return this.name!=undefined && this.name !=="";
}
}
const me=new Person();
if (me.hasName()) {
console.log(me.name.includes("a"));
}