打字稿中的Typeof运算符

时间:2018-09-19 11:20:36

标签: angular typescript

我不是打字稿方面的专家,我正在做一些示例来测试角度为2+的Http模块。 在调试时,我已在这段代码中指出:  当我单击红色按钮时,将调用函数removePost(post: Post){...}并在该函数中传递一个类型为“ Post”的对象,该对象又调用服务以删除沙盒中的下一行。

removePost(post: Post) {
    if (confirm('are You sure?')) {
      this.postService.removePost(post.id).subscribe(() => {
        this.posts.forEach((cur, index) => {
          if (post.id === cur.id) {
            this.posts.splice(index, 1);

          }
        });
      });
    }
  }

Image test debuging

当我尝试使用chrome进行测试调试时,我的疑惑开始了。从字面上到达服务的Post参数(将是一个对象)将直接转换为数字类型:

removePost(post:Post|number):Observable<Post>{

  const id=typeof post ==='number' ? post: post.id;
  const url=`${this.postsUrl}/${id}`;
  return  this.http.delete<Post>(url,httpOptions);
} 

我认为我可能不了解运算符typeof的工作方式。我的意思是在这段代码const id=typeof post ==='number' ? post: post.id;typeof是一个数字,因此将被设置为post而不是post.id,但是问题在于post对象 ...如何知道打字稿必须将对象转换为数字吗?这件事让我很困惑。...

3 个答案:

答案 0 :(得分:1)

在这里调用方法

this.postService.removePost(post.id)

因此postnumber的对象。

答案 1 :(得分:1)

Typescript将不执行任何运行时转换。您的代码指出postnumber | Post,因此removePost要么是number要么是Post。因此,这些调用中的任何一个都是有效的:

let p: Post = { } // a radom post from wherever
postService.removePost(p) // argument is Post and that is fine
postService.removePost(p.id) // argument is a number, that is fine too.

typeof的作用是找出我们在两种情况中的哪一种情况。如果typeof post ==='number'为真,则在第二种情况下,因此postnumber,如果为假,则在第一种情况下,post为{{1} }对象,我们可以访问Post属性以获取ID。

还要注意的是,id将被键入为id。这是由于称为类型防护的功能(请参见herehere),其中联合通过诸如number

之类的检查而变窄
typeof post ==='number'

答案 2 :(得分:1)

好问题。原因可能是因为您要将 post.id 传递给 removePost()方法。

在这种情况下,您可以正确使用 typeof 运算符,尽管在这种情况下不必使用,因为您显式传递了数字而不是post对象。因此,您的代码应该像这样工作:

removePost(postId:number):Observable<Post>{
  const url=`${this.postsUrl}/${postId}`;
  return  this.http.delete<Post>(url,httpOptions);
}

请注意,我将参数从post重命名为postId。

在您的屏幕截图中,我还注意到,对于 updatePost(),您正在传递post对象。作为建议,我会说您在选择时应保持一致。在遵循此模式的所有方法中,要么将id传递给只需要id的方法,要么传递post对象(仅当您需要从post对象访问更多属性时)。实际上,这不会影响功能,但是会改善代码的样式。

相关问题