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

Translate 1 file to ko - TypeScript 4.1.md #94

Closed
wants to merge 46 commits into from
Closed

Translate 1 file to ko - TypeScript 4.1.md #94

wants to merge 46 commits into from

Conversation

minsoo0715
Copy link

en

TypeScript 4.1.md 번역완료했습니다.
어색한 부분이 있거나 틀린 부분있으면 코멘트 부탁드립니다🙏
ref #6

@ghost
Copy link

ghost commented Jul 14, 2021

CLA assistant check
All CLA requirements met.

@github-actions
Copy link
Contributor

Thanks for the PR!

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

@github-actions
Copy link
Contributor

github-actions bot commented Jul 14, 2021

Translation of TypeScript 4.1.md

title: TypeScript 4.1
layout: docs
permalink: /ko/docs/handbook/release-notes/typescript-4-1.html

oneline: TypeScript 4.1 Release Notes

Template Literal Types

In TypeScript, string literal types enable you to model functions and APIs that anticipate a set of specific strings.

// @errors: 2345
function setVerticalAlignment(location: "top" | "middle" | "bottom") {
  // ...
}

setVerticalAlignment("middel");

This is pretty good in that the string literal type can spell check for string values by default.
It also has the advantage of being able to use string literals as property names in mapped types.
In this respect, string literals can be used like building blocks.

type Options = {
  [K in "noImplicitAny" | "strictNullChecks" | "strictFunctionTypes"]?: boolean;
};
// same as
//   type Options = {
//       noImplicitAny?: boolean,
//       strictNullChecks?: boolean,
//       strictFunctionTypes?: boolean
//   };

However, there are other cases where you can use those string literal types like architectural blocks: when you create other string literal types,

For the above reasons, Typescript 4.1 added a template literal string type.
This is template literal strings in JavaScripthas the same syntax as .
However, template literal string types are used where you define them.
If you use this with specific literal types, it combines the two values to create a new string literal type.

type World = "world";

type Greeting = `hello ${World}`;
//   ^?

What happens if you use it instead of a union type?

This generates a set of all string literals that each union members can represent.

type Color = "red" | "blue";
type Quantity = "one" | "two";

type SeussFish = `${Quantity | Color} fish`;
//   ^?

These can be used in more places than cute examples in release notes.

For example, various UI component libraries often provide a way to align vertically and horizontally, often "bottom-right"simply use a string like to sort.
"top", "middle", "bottom"vertical alignment, such as "left", "center", "right"When you combine a horizontal alignment, such as dash, between them, there are nine strings.

// @errors: 2345
type VerticalAlignment = "top" | "middle" | "bottom";
type HorizontalAlignment = "left" | "center" | "right";

// Takes
//   | "top-left"    | "top-center"    | "top-right"
//   | "middle-left" | "middle-center" | "middle-right"
//   | "bottom-left" | "bottom-center" | "bottom-right"

declare function setAlignment(value: `${VerticalAlignment}-${HorizontalAlignment}`): void;

setAlignment("top-left");   // works!
setAlignment("top-middel"); // error!
setAlignment("top-pot");    // error! but good doughnuts if you're ever in Seattle

An example of sorting the UI API A lot Despite this, this is still only a simple example in that we write it passively.
In fact, for the nine strings, it doesn't matter, but if you need a huge number of strings, you'll consider automatically generating them to save time for future type checks.

The real value of this comes from dynamically creating new string literals.
For example, if you import an object and create an almost identical object, makeWatchedObject Think of the API. and on Let's say you detect changes in properties with methods.

let person = makeWatchedObject({
  firstName: "Homer",
  age: 42, // give-or-take
  location: "Springfield",
});

person.on("firstNameChanged", () => {
  console.log(`firstName was changed!`);
});

Where the on method is "firstName"not "firstNameChanged" Note that you are listening to the event.

How do I type the on method?

type PropEventSource<T> = {
    on(eventName: `${string & keyof T}Changed`, callback: () => void): void;
};

/// 감시 대상 객체를 on 메소드와 함께 만들어서
/// 프로퍼티의 변화를 감시할 수 있게됩니다.
declare function makeWatchedObject<T>(obj: T): T & PropEventSource<T>;

As such, if an incorrect value comes in, you can create an error!

// @errors: 2345
type PropEventSource<T> = {
    on(eventName: `${string & keyof T}Changed`, callback: () => void): void;
};
declare function makeWatchedObject<T>(obj: T): T & PropEventSource<T>;
let person = makeWatchedObject({
  firstName: "Homer",
  age: 42, // 대략
  location: "Springfield",
});

// ---생략---
// error!
person.on("firstName", () => {});

// error!
person.on("frstNameChanged", () => {});

You can also use template literal types to do something special. : Inferred at the position of substitution (infer)

In the example above, you can identify the relevant eventNameYou can create a generic example that you deduce from the string part.

type PropEventSource<T> = {
    on<K extends string & keyof T>
        (eventName: `${K}Changed`, callback: (newValue: T[K]) => void ): void;
};

declare function makeWatchedObject<T>(obj: T): T & PropEventSource<T>;

let person = makeWatchedObject({
    firstName: "Homer",
    age: 42,
    location: "Springfield",
});

// 작동합니다! 'newName'의 타입은 'string'입니다.
person.on("firstNameChanged", newName => {
    // 'newName'의 타입은 'fistName'의 타입과 같습니다. 
    console.log(`new name is ${newName.toUpperCase()}`);
});

// 작동합니다! 'newAge'의 타입은 'number'입니다.
person.on("ageChanged", newAge => {
    if (newAge < 0) {
        console.log("warning! negative age");
    }
})

In generic methods onI created a .
on Method "firstNameChanged"If called as follows, TypeScript Kto determine if it is the type that matches the
To do this, TypeScript Kand "Changed"will contrast the "firstName" inferring string.
Once Typescript has figured it out, onMethods are used in the original object. firstNamewill bring its type. (The type in this case string is.)
Similarly "ageChanged"If called as, ageI will find the type of the professional. (The type in this case number is.)

Inference can be combined in different ways to decompose and reconstruct strings.
In fact, to help you modify this string literal type, we've added several utility type aliases to separate case. (e.g. converting lowercase letters to uppercase letters)

type EnthusiasticGreeting<T extends string> = `${Uppercase<T>}`

type HELLO = EnthusiasticGreeting<"hello">;
//   ^?

New type aliases Uppercase, Lowercase, Capitalize, UncapitalizeIs.

The front two replace all characters, and the back two replace only the first character.

For more information, see Check the original pull request. and Ongoing pull request to replace with type alias helperCheck it out too.

Key Remapping in Mapped Types

First of all, the mapping type is used to create new objects based on arbitrary keys,

type Options = {
  [K in "noImplicitAny" | "strictNullChecks" | "strictFunctionTypes"]?: boolean;
};
// same as
//   type Options = {
//       noImplicitAny?: boolean,
//       strictNullChecks?: boolean,
//       strictFunctionTypes?: boolean
//   };

Alternatively, you can create new object types based on different object types.

/// 'Partial<T>'가 'T'와 같지만, 각 프로퍼티는 선택 사항으로 표시되어 있음.
type Partial<T> = {
  [K in keyof T]?: T[K];
};

Until now, mapped types had to have keys provided to create new object types. However, in most cases, you can create a new key based on input, or filter the key.

This is why Typescript 4.1 asThis is why we allow the use of identifiers to relocate keys.

type MappedTypeWithNewKeys<T> = {
    [K in keyof T as NewKeyType]: T[K]
    //            ^^^^^^^^^^^^^
    //            이것이 새 문법입니다!
}

This new as Like the template literal type, clauses can easily create new properties by using the names of the old object properties.

type Getters<T> = {
    [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};

interface Person {
    name: string;
    age: number;
    location: string;
}

type LazyPerson = Getters<Person>;
//   ^?

and neveryou can filter the keys by creating .
Therefore, in some cases, additional Omit You don't need to use the helper type.

// 'kind' 프로퍼티를 삭제하기
type RemoveKindField<T> = {
    [K in keyof T as Exclude<K, "kind">]: T[K]
};

interface Circle {
    kind: "circle";
    radius: number;
}

type KindlessCircle = RemoveKindField<Circle>;
//   ^?

For more information, see: Original pull request on GithubCheck it out.

Recursive Condition Types

In JavaScript, functions that can be created and leveled container types at any level are common.
Like what Promiseexists in the instance .then() Let's think of a method.
.then(...)solves each promise until it finds a value that is "not promise", and crosses the value into a callback function.
In addition Arrayhow deep it is to flat out. flatA method exists.

For all practical intents and purposes, it is impossible to describe this in type systems in TypeScript.
There were a number of hacks for this, but in the end they looked very unreasonable.
This is why Typescript 4.1 has relaxed many restrictions on conditional types. - So you can model these patterns.
To make recursive type inference easier in Typescript 4.1, conditional types can now be referenced directly and recursively.
For example, if you want to use element types in a multidimensional array, deepFlatten A type is available.

type ElementType<T> = T extends ReadonlyArray<infer U> ? ElementType<U> : T;

function deepFlatten<T extends readonly unknown[]>(x: T): ElementType<T>[] {
  throw "not implemented";
}

// 모두 'number[]' 타입을 반환합니다.
deepFlatten([1, 2, 3]);
deepFlatten([[1], [2, 3]]);
deepFlatten([[1], [[2]], [[[3]]]]);

Similarly, in TypeScript 4.1, AwaitedBy using a 2 type, PromiseI release it and can hurt it.

type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T;

/// `promise.then(...)`과 비슷하지만, 타입에 대해서는 더 정확함.
declare function customThen<T, U>(
  p: Promise<T>,
  onFulfilled: (value: Awaited<T>) => U
): Promise<Awaited<U>>;

These recursive types are powerful but responsible and should be used with less.

First, these recursive types do a lot of work, thus increasing the type verification time.
It's fun to model the numbers in the Fibonaci row, but it's never going to .d.tsDon't do it in a file.

In addition, leaving compute-intensive, these types can reach the internal recursive depth limit for sufficiently complex inputs.
When the recursive limit is reached, a compile-time error occurs.
In general, it is better not to use these types at all than to fail to write them in a more realistic example.

SupplementsSee .

Checked Indexed Accesses (--noUncheckedIndexedAccess))

TypeScript is a index signatures it has a function called.
These signatures signal the type system that the user has access to arbitrary named features.

interface Options {
  path: string;
  permissions: number;

  // 추가된 프로퍼티들은 이 index signature에 의해 찾아집니다.
  [propName: string]: string | number;
}

function checkOptions(opts: Options) {
  opts.path; // string
  opts.permissions; // number
  // 모두 허용됩니다!
  // 모두 'string | number' 타입을 가집니다.
  opts.yadda.toString();
  opts["foo bar baz"].toString();
  opts[Math.random()].toString();
}

In the example above, Optionall additional additional string | number have an index signature that must have a type.

This is sometimes easy in that it's easy to know what you're doing, but the fact is that the most important value of JavaScript is that it doesn't support all possible property names.
Most types, like the old example, Math.random()The value of the property key created through will not exist.
Many users may not want these behaviors, and this --stringNullChecksmay feel as if you are not affected by a complete rigorous examination of the

That's why TypeScript 4.1 --noUncheckedIndexedAccessthe new flag.
In this mode, all the prop access and (e.g. foo.barindex access (e.g., foo["bar"]) are believed to be potentially undefined.
This is in the example above. opts.yaddaprice string | numberI do not have a 2 type string | number | undefinedmeans that you have a type of .
If you need to access a prop, you must first check the existence of this !) should be used.

// @errors: 2532
// @noUncheckedIndexedAccess
interface Options {
  path: string;
  permissions: number;

  // Extra properties are caught by this index signature.
  [propName: string]: string | number;
}
// ---cut---
function checkOptions(opts: Options) {
  opts.path; // string
  opts.permissions; // number

  // These are not allowed with noUncheckedIndexedAccess
  opts.yadda.toString();
  opts["foo bar baz"].toString();
  opts[Math.random()].toString();

  // Checking if it's really there first.
  if (opts.yadda) {
    console.log(opts.yadda.toString());
  }

  // Basically saying "trust me I know what I'm doing"
  // with the '!' non-null assertion operator.
  opts.yadda!.toString();
}

--noUncheckedIndexedAccesswill be strictly checked for access to the array, and it will also be checked in iterations that check the scope.

// @errors: 2532
// @noUncheckedIndexedAccess
function screamLines(strs: string[]) {
  // 에러가 발생할 것임.
  for (let i = 0; i < strs.length; i++) {
    console.log(strs[i].toUpperCase());
  }
}

If you don't need indexes, for-of Repeating or, forEachyou can use to access each element repeatedly.

// @noUncheckedIndexedAccess
function screamLines(strs: string[]) {
  // 정상적으로 작동
  for (const str of strs) {
    console.log(str.toUpperCase());
  }

  // 정상적으로 작동 
  strs.forEach((str) => {
    console.log(str.toUpperCase());
  });
}

This flag can be useful for catching out-of-bounds errors, but it will length your code longer. consequently --string It is not automatically activated through flags; However, if you're interested in this feature, feel free to try it to determine if it's right for your team's codebase.

Supplemental pull requestyou can learn more.

baseUrlabsent paths (paths without baseUrl)

Using path mapping is very common and is often used to simulate monorepo linking, for better import.

Unfortunately, to enable path mapping pathsTo specify baseUrlYou need to specify an option called.
This sometimes resulted in auto-imports getting the wrong path.
TypeScript 4.1 pathsThe options are baseUrl It can be used without options.
This fix helps avoid some of these issues.

checkJSof allowJS Built-in (checkJs Implies allowJs)

Previously, to inspect JavaScript projects, allowJSand checkJSshould have been set up.
This was a slightly annoying experience. consequently checkJSNow, allowJSbuilt in by default.
For more information, see this pull request..

React 17 JSX Factory (React 17 JSX Factories)

TypeScript 4.1 jsxand jsxs The factory function is supported by two new jsx compiler options.

  • react-jsx
  • react-jsxdev

These options are intended to separate production and development compilation individually.
Often, one option can be extended to another.
For example, for a production build, tsconfig.json Maybe this is the case.

// ./src/tsconfig.json
{
  "compilerOptions": {
    "module": "esnext",
    "target": "es2015",
    "jsx": "react-jsx",
    "strict": true
  },
  "include": ["./**/*"]
}

Also, this is probably the case for development builds.

// ./src/tsconfig.dev.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "jsx": "react-jsxdev"
  }
}

For more information, see Check out this PR

JSDoc @see Editor Support for Tags (Editor Support for the JSDoc) @see Tag)

JSDoc Tag @see Tags are now more powerfully supported by TypeScript and JavaScript.

This allows you to use features such as Go to Definition in a name marked with a dot after the tag.

For example, in a JSDco comment, firstI CMoving to the definition of behaves as shown in the following example.

// @filename: first.ts
export class C {}

// @filename: main.ts
import * as first from "./first";

/**
 * @see first.C
 */
function related() {}

Active contributors Wenlu WangDear This oneThank you for adding!

Big Change (Breaking Changes)

lib.d.tsOf changes (lib.d.ts Changes)

lib.d.tsmay have a changed set of APIs because of how the DOM type is automatically generated.
One of the specific changes is, Reflect.enumerateis excluded from ES2016.

abstract Members asynccan't be displayed as (abstract Members Can't Be Marked async)

abstractmembers are no longer asyncis not displayed as .
Here, callers are only interested in the return type.async The keyword has been removed.

any/unknowndeployment to the wrong location in (any/unknow Are Propagated in Falsy Positions)

In the old years, fooA type of anyor unknownphosphorus foo && somethingElseA type of somethingElseit was decided by the type of .

For example, in the old example, x The type {someProp: string} Was.

declare let foo: unknown;
declare let somethingElse: { someProp: string };

let x = foo && somethingElse;

However, in TypeScript 4.1, we decided to be more nervous about inferring this type.
anything &&if there is nothing known about the left type of , it affects the outside, not the right.

The most common pattern here is booleanwhen you see a match with , in particular, it tends to appear in presym functions.

function isThing(x: any): boolean {
  return x && typeof x === "object" && x.blah === "foo";
}

Often, the right solution is foo && someExpressionIn !!foo && someExpressionis to change to .

The parameters of resolve are no longer optional. (resolve's Parameters Are No Longer Optional in Promises)

When you write code like the bottom,

new Promise((resolve) => {
  doSomethingAsync(() => {
    doSomething();
    resolve();
  });
});

You should be able to see these errors.

  resolve()
  ~~~~~~~~~
error TS2554: Expected 1 arguments, but got 0.
  An argument for 'value' was not provided.

This is resolveno longer receive optional parameters. So basically, this should now pass a value.
Often this is Promiseto catch normal bugs while using .
A common way to solve this is to hand over the correct characters or hand over explicit typers.

new Promise<number>((resolve) => {
  //     ^^^^^^^^
  doSomethingAsync((value) => {
    doSomething();
    resolve(value);
    //      ^^^^^
  });
});

But sometimes resolve()there are times when a call must be made without an 0.
In this situation, PromiseExplicit to void You can hand over generic type numbers. (Example. Promise<void>like)
This new feature in TypeScript 4.1 void Transfer parameters can be optional.

new Promise<void>((resolve) => {
  //     ^^^^^^
  doSomethingAsync(() => {
    doSomething();
    resolve();
  });
});

TypeScript 4.1 provides a quick solution to help you resolve this issue.

Conditional deployments create optional property (Conditional Spreads Create Optional Property)

JavaScript { ... foo}Object variance, such as , is not performed on invalid values.
Therefore, in this code, { ... foo}and foo If the value is nullOr undefinedIf so, skip it.

Many users use it to spread it "conditionally" to their companies.

interface Person {
  name: string;
  age: number;
  location: string;
}

interface Animal {
  name: string;
  owner: Person;
}

function copyOwner(pet?: Animal) {
  return {
    ...(pet && pet.owner),
    otherStuff: 123,
  };
}

// optional chaning을 사용할 수도 있음

function copyOwner(pet?: Animal) {
  return {
    ...pet?.owner,
    otherStuff: 123,
  };
}

Here's what if, petIf it was declared pet.ownerthe provisions of the Otherwise, the properties do not unfold to the returned object.

copyOwnerThe return type of was previously a union type based on each variance.

{ x: number } | { x: number, name: string, age: number, location: string }

This modeled exactly how the work was done. What if petIf it was declared PersonAll the products from the Otherwise, no provision will be defined based on the result.
This is an all-or-nothing operation that makes it all-or-nothing.

However, this pattern has evolved to the extreme, with hundreds of spreads spreading across a single object, each potentially adding hundreds or thousands of properties.

This has been found to be prohibitively expensive and not very good in most situations, in the end for a variety of reasons.

In TypeScript 4.1, all optional property is available for the occasional returned type.

{
    x: number;
    name?: string;
    age?: number;
    location?: string;
}

In the end, it works more efficiently and becomes more readable.

For more information, See original fixes.
While this behavior is not completely consistent right now, we expect cleaner and more predictable results in future releases.

Mismatched parameters are no longer associated (Unmatched parameters are no longer related)

TypeScript provides parameters that do not match each other. any I associated it with a type.
Changes in TypeScript 4.1TypeScript completely skips this process.
This means that some specified cases do not fail, and some cases of overload resolution may fail.
For example, in Node.js util.promisifyIf the solution to the overload of typeScript 4.1 selects a different overload, sometimes it can cause new or other errors in the subsect.
To avoid errors, it would be best to use type assertion as a solution.

Generated by 🚫 dangerJS against 127b83d

Copy link
Contributor

@yeonjuan yeonjuan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@minsoo0715 번역 감사합니다. :) 전반적으로 문단 구분을 원본과 맞춰야 할 것 같습니다.

docs/documentation/ko/release-notes/TypeScript 4.1.md Outdated Show resolved Hide resolved
docs/documentation/ko/release-notes/TypeScript 4.1.md Outdated Show resolved Hide resolved
docs/documentation/ko/release-notes/TypeScript 4.1.md Outdated Show resolved Hide resolved
docs/documentation/ko/release-notes/TypeScript 4.1.md Outdated Show resolved Hide resolved
docs/documentation/ko/release-notes/TypeScript 4.1.md Outdated Show resolved Hide resolved
docs/documentation/ko/release-notes/TypeScript 4.1.md Outdated Show resolved Hide resolved
docs/documentation/ko/release-notes/TypeScript 4.1.md Outdated Show resolved Hide resolved
docs/documentation/ko/release-notes/TypeScript 4.1.md Outdated Show resolved Hide resolved
docs/documentation/ko/release-notes/TypeScript 4.1.md Outdated Show resolved Hide resolved
@yeonjuan
Copy link
Contributor

yeonjuan commented Aug 3, 2021

@minsoo0715 고생하셨습니다 :) 아직 전부다 자세히 읽어보진 않았습니다. 눈에 띄는 부분 코멘트 남겼습니다 👍

minsoo0715 and others added 29 commits August 8, 2021 21:03
@minsoo0715
Copy link
Author

꼼꼼한 리뷰 감사드립니다. 🙏 사소한 결점들이 너무 많네요.

This pull request was closed.
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.

2 participants