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

Fix unnecessary and undeleted text in Everyday Types.md #208

Merged
merged 1 commit into from
Feb 11, 2023

Conversation

0ldh
Copy link
Contributor

@0ldh 0ldh commented Jan 20, 2023

"Here's an example", "아래는 그 예시입니다" same meaning


스크린샷 2023-01-26 오후 10 40 26

옵셔널 프로퍼티� => 옵셔널 프로퍼티


@github-actions
Copy link
Contributor

Thanks for the PR!

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

@github-actions
Copy link
Contributor

Translation of Everyday Types.md

title: Everyday Types
layout: docs
permalink: /ko/docs/handbook/2/everyday-types.html

oneline: "primitive types of language."

This chapter covers the most common types found in JavaScript code and explains how they are described in TypeScript.
This article is not intended to cover everything, and more ways to create and use types will be covered in subsequent chapters.

Types are much more diverse than just typewriting. _location_may appear in
In addition to learning about the types themselves, we will also look at the cases when referencing types when creating new structs.

Let's start by revisiting some of the most basic and common types when writing JavaScript or TypeScript code.
These types are the key components of the more complex types that we will discuss later.

Primitive types: string, numberand boolean

Three very common uses in JavaScript Primitive typeto string, numberand booleanis available.
Each of these types has its own counterpart in TypeScript.
As you might expect, these types are used in JavaScript to value each type. typeof It has the same name that you would get when you used the operator.

  • stringsilver "Hello, world"Represents a string value such as
  • numbersilver 42represents a number such as . JavaScript does not have a separate runtime value for integers. int or floatThere is no such thing as All numbers are simply numberIs
  • booleansilver trueand falsehas only two values

String, Number, Booleanis a valid type, but it is extremely rare to use these special built-in types in code. All the time string, number, boolean Use a type.

array

[1, 2, 3]When specifying the type of an array such as number[] syntax. This syntax can be used with any type (for example, string[]is an array of strings).
The above type is Array<number>, and has the same meaning.
T<U> For syntax, see Generic Let's find out more when dealing with

[number]has a completely different meaning. Tuple type section.

any

TypeScript also provides any, and can be used when you do not want a specific value to cause type checking errors.

What is the type of value anyIf so, any attribute can be accessed for that value (the type of the returned value is also any), you can call it as if it were a function, assign (receive) it to any value of any type, or do anything else that is syntactically valid.

let obj: any = { x: 0 };
// 아래 이어지는 코드들은 모두 오류 없이 정상적으로 실행됩니다.
// `any`를 사용하면 추가적인 타입 검사가 비활성화되며,
// 당신이 TypeScript보다 상황을 더 잘 이해하고 있다고 가정합니다.
obj.foo();
obj();
obj.bar = 100;
obj = "hello";
const n: number = obj;

any Types can be useful when you don't want to redefine a long type just because of one purpose: to reassure TypeScript that there is nothing wrong with a particular line of code.

noImplicitAny

For an untyped value, if TypeScript cannot infer the type from the context, the compiler any Assigning a type is the default behavior.

However, this situation is usually not preferred. because anyis because no type checking is performed.
Compiler Flags noImplicitAnyIf you use implicitly anyraises an error in all cases that it considers.

Type notation for variables

const, varor let When declaring a variable, you can add a type notation to explicitly specify the type of the variable, which is optional.

let myName: string = "Alice";
//        ^^^^^^^^ 타입 표기

TypeScript is int x = 0;does not use the notation of "write type to left".
The type notation is always the object of the type. On the back Location.

In most cases, however, type notation is not required.
When possible, TypeScript automatically replaces the types in the code. _inference_I will try.
For example, the type of a variable is inferred based on the type of the initial value of that variable.

// 타입 표기가 필요하지 않습니다. 'myName'은 'string' 타입으로 추론됩니다.
let myName = "Alice";

In most cases, you don't need to explicitly learn inference rules.
If you're just getting started with TypeScript, try using as few typings as possible. You'll be surprised to learn that you don't need a lot of types to fully understand the flow of code.

function

Functions are the primary means of sending and receiving data in JavaScript.
TypeScript allows you to specify the input and output types of functions.

Parameter type notation

When you declare a function, you can mark the type after each parameter to declare the parameter types that the function will accept.
The parameter type is indicated after the parameter name.

// 매개변수 타입 표기
function greet(name: string) {
  //                 ^^^^^^^^
  console.log("Hello, " + name.toUpperCase() + "!!");
}

If a type is specified in a parameter, the arguments to that function are checked.

// @errors: 2345
declare function greet(name: string): void;
// ---cut---
// 만약 실행되면 런타임 오류가 발생하게 됩니다!
greet(42);

Even if you don't specify a type in the parameter, TypeScript still checks whether the correct number of arguments are passed.

Return Type Notation

The return type can also be indicated.
The return type is indicated after the parameter list.

function getFavoriteNumber(): number {
  //                        ^^^^^^^^
  return 26;
}

As with the type notation of variables, it is common that the return type does not need to be indicated. Because TypeScript is contained in that function, return Because we will infer the return type based on the statement.
The type notation used in the example above does not have much meaning.
Sometimes there is code that performs explicit typing for documentation purposes, to prevent incorrect modifications to the code, or out of extreme personal preference.

Anonymous functions

Anonymous functions are a little different from function declarations.
If you can see where a function is located in your code and figure out how it will be called, TypeScript automatically assigns a type to the function's parameters.

Below is an example.

// @errors: 2551
// 아래 코드에는 타입 표기가 전혀 없지만, TypeScript는 버그를 감지할 수 있습니다.
const names = ["Alice", "Bob", "Eve"];

// 함수에 대한 문맥적 타입 부여
names.forEach(function (s) {
  console.log(s.toUppercase());
});

// 화살표 함수에도 문맥적 타입 부여는 적용됩니다
names.forEach((s) => {
  console.log(s.toUppercase());
});

parameter sDespite the fact that TypeScript is not typed, TypeScript sWith the inferred type of the array to find out the type of forEach We used the type of the function.

This process is Contextual type assignment, because the function is executed _context_This is because we can know the type that the function should have.
Similar to reasoning rules, you don't have to explicitly learn how this process happens, but if this _How it actually happens_This will help you identify cases where type notation is unnecessary.
We'll look at examples later where the context in which a value occurs affects the type of that value.

Object Type

Except for primitive types, the most common types encountered are _Object Type_Is.
An object is a JavaScript value that has a property, and that's usually the case!
To define an object type, simply list the object's properties and the types of each property.

For example, the function below accepts as arguments an object that appears to be coordinates.

// 매개 변수의 타입은 객체로 표기되고 있습니다.
function printCoord(pt: { x: number; y: number }) {
  //                      ^^^^^^^^^^^^^^^^^^^^^^^^
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });

Above, the parameters are xand yis represented by a type consisting of two properties, and both values are number Type.
When distinguishing each property , or ;, and the notation of the last separator is optional.

The type notation of each property is also optional.
If no type is specified, the property is any type.

Optional Properties

An object type is an optional type that specifies the type of some or all of its properties, i.e. _Optional_Can be specified as
After the property name ?You can do this.

function printName(obj: { first: string; last?: string }) {
  // ...
}
// 둘 다 OK
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });

In JavaScript, when accessing a property that does not exist, a run-time error does not occur. undefined You will get the value.
Because of this, the optional property Read When using that value, before undefinedYou need to check whether it is.

// @errors: 2532
function printName(obj: { first: string; last?: string }) {
  // 오류 - `obj.last`의 값이 제공되지 않는다면 프로그램이 멈추게 됩니다!
  console.log(obj.last.toUpperCase());
  if (obj.last !== undefined) {
    // OK
    console.log(obj.last.toUpperCase());
  }

  // 최신 JavaScript 문법을 사용하였을 때 또 다른 안전한 코드
  console.log(obj.last?.toUpperCase());
}

Union Type

TypeScript's type system allows you to create new types using a variety of operators based on existing types.
Now that you know how to use some types, you can use these types In combination It's time to try it out in an interesting way.

Defining Union Types

The first way to combine types is to Union It's about using types.
A union type is created using two or more different types, and the value of the union type is one of the types used in the type combination. _Anything One_can be as a type.
Each type used in the combination is a union type _member_Call.

Let's write a function that can accept a string or a number.

// @errors: 2345
function printId(id: number | string) {
  console.log("Your ID is: " + id);
}
// OK
printId(101);
// OK
printId("202");
// 오류
printId({ myID: 22342 });

Using the Union Type

Values that match the union type Provided It's that simple. You can provide a type corresponding to one of the members of the union type.
A union-type value is in the code When it exists, How should we use it?

When dealing with unions in TypeScript, the all Allowed only if the operation is valid for the member.
For example string | numberIn the case of the union type, string You cannot use methods that are valid only for types.

// @errors: 2339
function printId(id: number | string) {
  console.log(id.toUpperCase());
}

To work around this, change the union in your code to Narrow This is the same as what happens in JavaScript without typewriting.
_Narrow_occurs when TypeScript can infer a value to a more specific type based on the structure of the code.

For example, TypeScript only uses string Value only typeof As the result of the operation "string"I know I can have

function printId(id: number | string) {
  if (typeof id === "string") {
    // 이 분기에서 id는 'string' 타입을 가집니다

    console.log(id.toUpperCase());
  } else {
    // 여기에서 id는 'number' 타입을 가집니다
    console.log(id);
  }
}

Another example is Array.isArrayis to use a function like

function welcomePeople(x: string[] | string) {
  if (Array.isArray(x)) {
    // 여기에서 'x'는 'string[]' 타입입니다
    console.log("Hello, " + x.join(" and "));
  } else {
    // 여기에서 'x'는 'string' 타입입니다
    console.log("Welcome lone traveler " + x);
  }
}

else Note that branch statements do not require any processing. xThe type of string[]If not, xThe type of must be stringwill be.

Sometimes all members of a union may have something in common.
For example, arrays and strings are both slice Embeds the method.
If all members of a union have a property in common, they can use that property without narrowing it.

// 반환 타입은 'number[] | string'으로 추론됩니다
function getFirstThree(x: number[] | string) {
  return x.slice(0, 3);
}

Union is semantically union, but in reality, the union type is the property of _intersection_It seems to be pointing to , which can make you feel confused.
This is no coincidence. _Union_The name comes from type theory.
number | string Union Each type has its own type About values It is constructed by taking a union.
Given two sets and the properties for each set, the _Union_There are characteristics of each of the _intersection_Please note that only applies.
For example, suppose one room has tall people wearing hats, and another room has Spanish-speaking people wearing hats. If you combine the two rooms at this time, all What we do know about people is that everyone wears a hat.

Type alias

Until now, when using object types and union types, we have indicated the types directly.
This is convenient, but there are times when you want to reuse the same type more than once or by another name.

_Type alias_exists for this very occasion, _type_For _name_Provides.
The syntax of the type alias is as follows.

type Point = {
  x: number;
  y: number;
};

// 앞서 사용한 예제와 동일한 코드입니다
function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}

printCoord({ x: 100, y: 100 });

You can use type aliases to give new names to all types, not just object types.
For example, you can give a type alias to a union type as shown below.

type ID = number | string;

Type aliases are merely Please note that it is nothing more than an alias. In other words, using type aliases does not create distinct "multiple versions" of the same type.
To use an alias is to create a new type with a separate name.
In other words, the code below is as incorrect as It can be seen However, this is normal in TypeScript because each type is an alias for the same type.

declare function getInput(): string;
declare function sanitize(str: string): string;
// ---cut---
type UserInputSanitizedString = string;

function sanitizeInput(str: string): UserInputSanitizedString {
  return sanitize(str);
}

// 보안 처리를 마친 입력을 생성
let userInput = sanitizeInput(getInput());

// 물론 새로운 문자열을 다시 대입할 수도 있습니다
userInput = "new input";

interface

_Declaring an Interface_is another way to create object types.

interface Point {
  x: number;
  y: number;
}

function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}

printCoord({ x: 100, y: 100 });

Similar to using type aliases, the example code above behaves as if it were using an arbitrary anonymous object with no type.
TypeScript is only printCoordof the value passed to _rescue_Only interested. That is, whether it has the predicted property or not.
As such, the fact that TypeScript is only interested in the structure and capabilities of the type means that TypeScript Structured That is why it is called a type system.

Differences between type aliases and interfaces

Type aliases and interfaces are very similar, and in most cases you are free to choose one or the other.
interfaceMost of the functions of type, can be used in . The most important difference between the two is that types cannot be opened to add new properties, whereas interfaces can always be extended.

인터페이스 타입

인터페이스 확장하기

interface Animal {
  name: string
}
interface Bear extends Animal { honey: boolean }
const bear = getBear() bear.name bear.honey

교집합을 통하여 타입 확장하기

type Animal = {
  name: string
}
type Bear = Animal & { honey: Boolean }
const bear = getBear(); bear.name; bear.honey;

기존의 인터페이스에 새 필드를 추가하기

interface Window {
  title: string
}
interface Window { ts: TypeScriptAPI }
const src = 'const a = "Hello World"'; window.ts.transpileModule(src, {});

타입은 생성된 뒤에는 달라질 수 없다

type Window = {
  title: string
}
type Window = { ts: TypeScriptAPI }
// Error: Duplicate identifier 'Window'.

We'll learn more about the above concepts in later chapters, so don't worry if you don't understand them now.

In most cases, you can choose between interfaces and types based on your personal preference, and TypeScript will suggest other choices if necessary. If you're not sure, first interfaceWhen problems occur after using typePlease use

Type assertion

Sometimes you know better information about the type of a value than TypeScript.

For example, in code: document.getElementByIdIf TypeScript is used, HTMLElement During _something_is returned, whereas you can always use the ID used on the page HTMLCanvasElementmay already know that is returned.

In this case, _Type assertion_to make the type more specific.

const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;

As with type notation, type assertions are removed by the compiler and do not affect the run-time behavior of your code.

The use of angle brackets is also (if the code is .tsx if it is not a file), which has the same meaning.

const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");

Remember: type assertions are removed at compile time, so no checks are made during runtime.
Even if the type assertion is incorrect, an exception is thrown, or nullwill not be generated.

In TypeScript, More specific or Less specific Only type assertions that convert to a version of the type are allowed.
These rules prevent "impossible" coercion, such as:

// @errors: 2352
const x = "hello" as number;

This rule is sometimes overly conservative, allowing for complex but valid coercion.
In this case, you can use two assertions. any(or introduce it later unknown) first, then convert to the desired type.

declare const expr: any;
type T = { a: 1; b: 2; c: 3 };
// ---cut---
const a = (expr as any) as T;

Literal type

stringand numberIn addition to the general type, Specific String and numeric values can be specified at type positions.

To understand this, consider the various methods provided for variable declarations in JavaScript. varand let You can change the types of values that can be stored in all variables. constThis is not possible. These characteristics are reflected in the way TypeScript creates types for literal values.

let changingString = "Hello World";
changingString = "Olá Mundo";
// 변수 `changingString`은 어떤 문자열이든 모두 나타낼 수 있으며,
// 이는 TypeScript의 타입 시스템에서 문자열 타입 변수를 다루는 방식과 동일합니다.
changingString;
// ^?

const constantString = "Hello World";
// 변수 `constantString`은 오직 단 한 종류의 문자열만 나타낼 수 있으며,
// 이는 리터럴 타입의 표현 방식입니다.
constantString;
// ^?

Literal types are not very meaningful on their own.

// @errors: 2322
let x: "hello" = "hello";
// OK
x = "hello";
// ...
x = "howdy";

A variable that can only have one value is not very useful!

But the literal is a union and When used together,, You will be able to express more useful concepts. For example, you might define a function that can accept only certain kinds of values as arguments.

// @errors: 2345
function printText(s: string, alignment: "left" | "right" | "center") {
  // ...
}
printText("Hello, world", "left");
printText("G'day, mate", "centre");

Numeric literal types can be used in the same way.

function compare(a: string, b: string): -1 | 0 | 1 {
  return a === b ? 0 : a > b ? 1 : -1;
}

Of course, it can also be used with non-literal types.

// @errors: 2345
interface Options {
  width: number;
}
function configure(x: Options | "auto") {
  // ...
}
configure({ width: 100 });
configure("auto");
configure("automatic");

There is another literal type. It's a bull literal type.
There are only two types of Bull literals, which, as you might expect, trueand falseIs.
boolean The type itself is actually just true | false It is an alias of the union type.

Literal reasoning

When you initialize a variable using an object, TypeScript assumes that the object's properties can change their values in the future.
For example, suppose you write the following code:

declare const someCondition: boolean;
// ---cut---
const obj = { counter: 0 };
if (someCondition) {
  obj.counter = 1;
}

If the existing value is 0In the field that was 1TypeScript does not consider it an error.
To put it another way, obj.counterThe must number You must have a type, 0 It means you can't have a literal type. Because the type is Read and writing This is because it is used to determine both actions.

The same applies to strings.

// @errors: 2345
declare function handleRequest(url: string, method: "GET" | "POST"): void;
// ---cut---
const req = { url: "https://example.com", method: "GET" };
handleRequest(req.url, req.method);

In the example above, req.methodThe stringNot inferred as, "GET"It is not inferred from. reqThe time of creation of and handleRequestCode evaluation can occur at any time between the calls of req.methodat "GUESS", so TypeScript determines that the above code is in error.

There are two ways to resolve these cases:

  1. You can add a type assertion in either place to change the reasoning method.

    declare function handleRequest(url: string, method: "GET" | "POST"): void;
    // ---cut---
    // 수정 1:
    const req = { url: "https://example.com", method: "GET" as "GET" };
    // 수정 2
    handleRequest(req.url, req.method as "GET");

    Fix 1 req.methodAlways go Literal type "GET"Intended to win, and accordingly, in the corresponding field "GUESS"We will prevent the case of substitution of such a value."
    Fix 2 says, "For some reason, req.methodprice "GET"as a value."

  2. as constto convert an entire object to a literal type.

    declare function handleRequest(url: string, method: "GET" | "POST"): void;
    // ---cut---
    const req = { url: "https://example.com", method: "GET" } as const;
    handleRequest(req.url, req.method);

as const The suffix is common constIt works similarly to , for all properties of that object. string or numberEnsures that values of literal types that are not more general types such as are assigned to them.

nulland undefined

In JavaScript, there are two kinds of raw values, one that points to an empty value or an uninitialized value. straight nulland undefinedIs.

TypeScript has two types of the same name corresponding to each value. _type_exists. The operation method of each type is strictNullChecks It depends on whether the option is set.

strictNullChecksis not set.

strictNullChecksprice If it is not set, what value null or undefinedEven if it can be, you can approach the value as usual, nulland undefinedcan be assigned to any type of variable.
This is similar to how languages that do not check for nulls (C#, Java, etc.) behave.
The lack of null checking is also a major cause of bugs. For no apparent reason, throughout the code strictNullChecks It is always recommended to set the option.

strictNullChecks When set

strictNullChecksprice If it is set, what value null or undefined, you should test the value before using any method or property with it.
Before Using Optional Properties undefined As with checking whether or not, _Narrow_Through nullYou can perform a check on values that can be days.

function doSomething(x: string | undefined) {
  if (x === undefined) {
    // 아무 것도 하지 않는다
  } else {
    console.log("Hello, " + x.toUpperCase());
  }
}

Non-null assertion operator (suffix !)

In TypeScript, you can use a type without explicit checking. nulland undefinedProvides a special syntax to remove the .
After the expression !, the value of which is null or undefinedis a type affirmation that it is not.

function liveDangerously(x?: number | undefined) {
  // 오류 없음
  console.log(x!.toFixed());
}

Like other type assertions, this syntax does not change the run-time behavior of the code. ! The operator must have that its value is null or undefinedprice Is not It should only be used.

Enumeration

An enumeration is a feature that TypeScript adds to JavaScript that means that what values _A set of constants with names_The ability to restrict to one of the values belonging to the DataSet. Unlike most TypeScript features, this feature has a type level in JavaScript. Is not, a feature that is added at the language and runtime level. So you may need to know what an enumeration is, but if you don't have a clear understanding of how to use it, you might want to hold off on using it. For more information about enumerations: Enumeration documentsPlease read it.

Infrequently used primitive types

In addition to the aforementioned types, we'll cover the rest of the JavaScript primitive types that exist in the type system.
Of course, we won't go into depth here.

bigint

Since ES2020, primitive types have been added to JavaScript to handle very large integers. straight bigintIs.

// @target: es2020

// BigInt 함수를 통하여 bigint 값을 생성
const oneHundred: bigint = BigInt(100);

// 리터럴 구문을 통하여 bigint 값을 생성
const anotherHundred: bigint = 100n;

For more information about BigInt, see TypeScript 3.2 Release NotesYou can check it out at .

symbol

symbolis a primitive type that can be used to generate globally unique reference values. Symbol() It can be created through functions.

// @errors: 2367
const firstName = Symbol("name");
const secondName = Symbol("name");

if (firstName === secondName) {
  // 절대로 일어날 수 없습니다
}

For more information about Symbol, see Symbol documentYou can check it out at .

Generated by 🚫 dangerJS against 2284e8d

@bumkeyy
Copy link
Contributor

bumkeyy commented Feb 11, 2023

@bb8dd

수정 감사합니다!

@bumkeyy
Copy link
Contributor

bumkeyy commented Feb 11, 2023

LGTM

@github-actions github-actions bot merged commit 662594d into microsoft:main Feb 11, 2023
@github-actions
Copy link
Contributor

Merging because @bumkeyy is a code-owner of all the changes - thanks!

@0ldh 0ldh deleted the undeletedText_fontBroken branch February 11, 2023 13:37
@0ldh 0ldh restored the undeletedText_fontBroken branch February 13, 2023 01:45
@0ldh 0ldh deleted the undeletedText_fontBroken branch February 13, 2023 01:45
@0ldh 0ldh restored the undeletedText_fontBroken branch February 13, 2023 01:51
@0ldh 0ldh deleted the undeletedText_fontBroken branch February 13, 2023 01:51
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