我可以在打字稿中使用“is”作为属性吗?

问题描述 投票:0回答:1

我想使用“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"));
}

但我不知道这是否可能。 我检查了文档,我发现的唯一示例是缩小参数类型。

typescript
1个回答
0
投票

您可以像这样使用它,但是空字符串或非空字符串没有特定的类型,因此您可以使用一些品牌类型:

广场

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"));
}
© www.soinside.com 2019 - 2024. All rights reserved.