`in` 关键字在打字稿中有什么作用? [英] What does the `in` keyword do in typescript?

查看:30
本文介绍了`in` 关键字在打字稿中有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用它,但我在文档中找不到任何解释.我想要一个准确的定义,以便我能更好地理解它.

I know how to use it, but I cannot find any explanation on it in docs. I'd like an accurate definition so that I could understand it better.

我的意思是在映射类型中使用的 in,而不是 js 操作符.

I mean the in used in mapped types, not the js operator.

推荐答案

这是标准的 in Javsacript 运算符.您可以在此处阅读更多文档,但是小故事是

This is the standard in Javsacript operator. You can read more documentation here, but the short story is

如果指定的属性在指定的对象中,则 in 运算符返回 true.语法是:

The in operator returns true if the specified property is in the specified object. The syntax is:

propNameOrNumber in objectName

其中 propNameOrNumber 是表示属性名称或数组索引的字符串或数值表达式,objectName 是对象的名称.

where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

在 Typescript 中,in 运算符还充当类型保护,如所述这里

In Typescript the in operator also acts as a type guard as described here

interface A {
  x: number;
}
interface B {
  y: string;
}

let q: A | B = ...;
if ('x' in q) {
  // q: A
} else {
  // q: B
}


编辑

in 在打字稿中的另一个含义是映射类型定义.您可以在手册拉取请求.in 关键字在此处用作语法的一部分,用于迭代键联合中的所有项目.

An alternative meaning of in in typescript is in mapped type definition. You can read about them in the handbook or in the pull request. The in keyword is used there as part of the syntax to iterate over all the items in a union of keys.

interface Person {
    name: string;
    age: number;
}
type Partial<T> = {
    [P in keyof T]?: T[P]; // P will be each key of T
}
type PersonPartial = Partial<Person>; // same as { name?: string;  age?: number; }

这篇关于`in` 关键字在打字稿中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆