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 Typeof Type Operator.md in zh-CN #180

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

EnochGao
Copy link

translate Typeof Type Operator.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

Translation of Typeof Type Operator.md

title: The Typeof type operator
layout: docs
permalink: /zh/docs/handbook/2/typeof-types.html
oneline: "Use the typeof type operator in the context of type."

translatable: true

typeof Type operator

JavaScript already has one typeof operator, you can in expression Use in context:

// 打印出 "string"
console.log(typeof "Hello world");

TypeScript added one typeof operator that allows you to use it in type It is used in context to reference variables or properties type

let s = "hello";
let n: typeof s;
//  ^?

This is not very useful for primitive types, but in combination with other type operators, you can use it typeof Convenient representation of multiple forms.
For example, let's start with a predefined type ReturnType<T> Start viewing. It accepts one Function type And generate the return type of the function:

type Predicate = (x: unknown) => boolean;
type K = ReturnType<Predicate>;
//   ^?

If we try to use on the function name ReturnType , we will see a guiding error:

// @errors: 2749
function f() {
  return { x: 10, y: 3 };
}
type P = ReturnType<f>;

Remember,values and types Not the same thing. To reference the function f The type of value we use typeof

function f() {
  return { x: 10, y: 3 };
}
type P = ReturnType<typeof f>;
//   ^?

limit

TypeScript intentionally limits its usability typeof The kind of expression.

Specifically, only on identifiers (i.e. variable names) or their properties typeof is legal.
This helps avoid confusing traps of writing code that you think is executing but isn't:

// @errors: 1005
declare const msgbox: () => boolean;
// type msgbox = any;
// ---cut---
// 以为等同于 ReturnType<typeof msgbox>,实际是错误的
let shouldContinue: typeof msgbox("Are you sure you want to continue?");

Generated by 🚫 dangerJS against 2e48ba0

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

2 participants