Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: translate Indexed Access Types.md in zh-CN #193

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

EnochGao
Copy link

translate Indexed Access Types.md in zh-CN

@github-actions
Copy link
Contributor

Thanks for the PR!

This section of the codebase is owned by @Kingwl - if they write a comment saying "LGTM" then it will be merged.

@github-actions
Copy link
Contributor

github-actions bot commented Dec 16, 2022

Translation of Indexed Access Types.md

title: Index access type
layout: docs
permalink: /zh/docs/handbook/2/indexed-access-types.html

oneline: "Use Type['a'] syntax to get a subset of a type"

We can use Index access type to find another type of specific property:

type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];
//   ^?

The type being indexed is itself a type, so it is perfectly possible to use union,keyof or other types:

type Person = { age: number; name: string; alive: boolean };
// ---cut---
type I1 = Person["age" | "name"];
//   ^?

type I2 = Person[keyof Person];
//   ^?

type AliveOrName = "alive" | "name";
type I3 = Person[AliveOrName];
//   ^?

If you try to index a property that doesn't exist, you'll even see an error:

// @errors: 2339
type Person = { age: number; name: string; alive: boolean };
// ---cut---
type I1 = Person["alve"];

Another example of using an arbitrary type of index is using number to get the type of the array element. We can relate it to typeof Used together, it is convenient to get the type of array literal elements:

const MyArray = [
  { name: "Alice", age: 15 },
  { name: "Bob", age: 23 },
  { name: "Eve", age: 38 },
];

type Person = typeof MyArray[number];
//   ^?
type Age = typeof MyArray[number]["age"];
//   ^?
// Or
type Age2 = Person["age"];
//   ^?

Indexes can only function on types above, which means they cannot be used const to establish a variable reference:

// @errors: 2538 2749
type Person = { age: number; name: string; alive: boolean };
// ---cut---
const key = "age";
type Age = Person[key];

However, you can use type aliases for similar refactoring:

type Person = { age: number; name: string; alive: boolean };
// ---cut---
type key = "age";
type Age = Person[key];

Generated by 🚫 dangerJS against d98e50d

@EnochGao
Copy link
Author

@Kingwl 麻烦处理一下中文相关的翻译吧,我看积累好多了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant