Skip to content

[ko] Handbook - The Basics - #73

Merged
github-actions[bot] merged 7 commits into
microsoft:mainfrom
cadenzah:translation/the-basics
May 14, 2021
Merged

github-actions[bot] merged 7 commits into
microsoft:mainfrom
cadenzah:translation/the-basics

Conversation

@cadenzah

@cadenzah cadenzah (cadenzah) commented May 2, 2021 •

Copy link
Copy Markdown
Contributor

@ghost

Deleted user (ghost) commented May 2, 2021 •

Copy link
Copy Markdown

CLA assistant check
All CLA requirements met.

@github-actions

github-actions Bot commented May 2, 2021

Copy link
Copy Markdown
Contributor

Thanks for the PR!

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

@github-actions

github-actions Bot commented May 2, 2021 •

Copy link
Copy Markdown
Contributor
Translation of Basics.md

title: The Basics
layout: docs
permalink: /ko/docs/handbook/2/basic-types.html
oneline: "The first step in learning TypeScript: the basic type."
preamble: >

Welcome to the first chapter of the handbook, and if you're new to TypeScript,Getting StartedWe recommend that you read one of the guide documents first.

Every value in JavaScript has its own built-in behavior, which can be confirmed by running various operations.
This may sound a little abstract, as a simple example. messageHere are some operations you can perform on a variable named.

// 'message'의 프로퍼티 'toLowerCase'에 접근한 뒤
// 이를 호출합니다
message.toLowerCase();

// 'message'를 호출합니다
message();

If you analyze the code above, first of all, the first line of executable code toLowerCaseand then call it.
On the second line, messageyou are trying to call directly.

but messageIf you don't know what the value of is - usually yes - I can't say for sure what the execution result of the code above is.
The behavior of each operation depends completely on what value it had at first.

  • messageIs it callable?
  • toLowerCasedo you have a provision called?
  • If you have, toLowerCase Is it also callable?
  • If both values can be called, what does each return?

These questions are common when we write code in JavaScript, and we always want to make sure we don't miss out on all the little things that come with it.

messageis defined as follows:

const message = "Hello World!";

As you may have guessed, here message.toLowerCase()If we run , we will get a value where the same string consists only of lowercase letters.

So what about the second line of code you saw earlier?
If you're familiar with JavaScript, you know it won't run with exceptions.

TypeError: message is not a function

I think it would be great if we could prevent mistakes like this in advance.

The JavaScript runtime is a value of type, that is, to determine what behavior and abilities the value has.
That's what TypeErroris what implies. In the example above, the string "Hello World"can't be called as a function.

Some values, for example, stringand numberFor values of the same primitive type as typeof Operators let you know the type of each value at the time of execution.
However, there is no mechanism at the time of executing the type of value, for example, for function values, as mentioned earlier.
For example, let's look at the following functions:

function fn(x) {
  return x.flip();
}

In the code above, an object passed as an flipthat the above function will work well only if we have to read the code you'll know. However, JavaScript doesn't know this information that we know while the code is running.
Pure JavaScript fnThe only way to know what actions a particular value is performing is to call it and see what happens.
This behavior makes predictions difficult before code is executed. In other words, it's hard to know what your code will look like while you're writing it.

In this respect, _type_what value is fn, and some values are described as failing executions.
JavaScript is only Dynamic You only need to run the code to see what happens.

The alternative to this is Static Code is executed using a type system ago predicting the code.

Static type checking

Seen stringwhen you want to call it as a function, TypeErrorLet's go back to the story.
Most people I don't want to see an error when I run the code. It is considered a bug!
And when we write new code, we do our best not to create new bugs.

If you add a little code here, save the file, and run the code again, and you'll see the error right away, you'll be able to isolate the problem quickly. But that doesn't always be the case.
You may not be able to find any potential errors because you haven't tested the feature enough!
Or, if you're lucky enough to find an error, you may end up digging deep into your code unintentionally, going through a significant refactoring and adding new code.

Ideally, you want to run the code ago It would be nice if you had a tool to spot these bugs in advance.
That's what static type checkers like TypeScript do.
_Static type system_explains the shape and behavior of the values used in the program we created.
Type Checkers, such as TypeScript, use this information to tell us when a program is not working properly.

// @errors: 2349
const message = "hello!";

message();

If you run the last example above in TypeScript, you'll first see the error message before the code runs.

Execution failure, not exception

So far, we've covered runtime errors. This is the case if the JavaScript runtime tells us something is strange.
These errors are how JavaScript should respond in the event of an unexpected problem ECMAScriptthis is because it provides explicit procedures in .

For example, according to the statement, an error occurs when you attempt to make a call for something that is not callable.
This may sound like "action of course," but even if someone tries to access a properties that don't exist in an object, they may also think they should throw an error.
But instead, JavaScript reacts completely differently. undefinedreturns .

const user = {
  name: "Daniel",
  age: 26,
};

user.location; // undefined 를 반환

Ultimately, a static type system should tell you which code is considered an error within a static type system, even if it is "valid" JavaScript code that does not cause an error.
In TypeScript, the code below locationcauses an error that is not defined.

// @errors: 2339
const user = {
  name: "Daniel",
  age: 26,
};

user.location;

Although this sometimes results in the sacrifice of expressive flexibility, this is not an explicit bug, but it is aimed at catching cases that are considered a bug.
And TypeScript has these invisible bugs pretty much hold it.

For example, a typo,

// @noErrors
const announcement = "Hello World!";

// 바로 보자마자 오타인지 아실 수 있나요?
announcement.toLocaleLowercase();
announcement.toLocalLowerCase();

// 아마 아래와 같이 적으려 했던 것이겠죠...
announcement.toLocaleLowerCase();

Unso caller functions,

// @noUnusedLocals
// @errors: 2365
function flipCoin() {
  // 본래 의도는 Math.random()
  return Math.random < 0.5;
}

Or basic logical errors.

// @errors: 2367
const value = Math.random() < 0.5 ? "a" : "b";
if (value !== "a") {
  // ...
} else if (value === "b") {
  // 이런, 이 블록은 실행되지 않겠군요
}

Types as programming tools

TypeScript catches bugs when we make mistakes in our code.
That's good, but TypeScript Let's go further here. It prevents us from making mistakes at the very moment.

Type Checker has relevant information to help us check whether we are accessing the correct properties on a variable or other properties.
With this information, type checkers can _proposition_will be able to do so.

In other words, TypeScript can be used to modify code, provide error messages as we type code, or provide code completion.
This is commonly mentioned when talking about tooling in TypeScript.

// @noErrors
// @esModuleInterop
import express from "express";
const app = express();

app.get("/", function (req, res) {
  res.sen
//       ^|
});

app.listen(3000);

TypeScript values programming tools, including code completion and error message capabilities.
Code editors that support TypeScript provide features such as "Quick Fixes", which automatically correct errors, refactoring easy to reorgant code, useful navigation to quickly move to the definition of variables, and searching for all references to a given variable.
All of these features are based on type checkers and operate completely cross-platform. The code editor you use mostly supports TypeScriptchances of being made.

tsc, TypeScript compiler

We've talked about type testing so far, but still type _Checker_has not been used.
Our new friends tsc, let's share the first conversation with the TypeScript compiler.
First, let's install using npm.

npm install -g typescript

If you run the code above, the TypeScript compiler tscis globally installed.
tscLocal node_modules If you want to run it from a package, npx Alternatively, you can use a similar tool.

Now go to an empty folder and click hello.tsLet's write a .

// 세상을 맞이하세요.
console.log("Hello world!");

Note that no underlining has been underlined on the code. This "hello world" program has the same look as the "hello world" program that you write in JavaScript.
And now typescript Installed with the package tsc Run commands to perform type checks.

tsc hello.ts

Voila!

Wait, exactly _what_It's "voila" and it's out, right?
tscI ran it, but nothing happened!
Well, there was no type error, nothing was reported, so no output appeared on the console.

But if we look back, we're going to file I got the output.
If you look at the current directory, hello.ts Next to the file hello.js You can see that the file is there.
This tscLet's hello.ts The file as a JavaScript file Compile or _metamorphosis_it's a result.
And if you look at it, TypeScript .ts After processing the file, you can see what you've spit out.

// 세상을 맞이하세요.
console.log("Hello world!");

In this case, there was very little that TypeScript had to transform, so we had the same result that we wrote in the first place.
The compiler tries to produce clean, readable code that looks like it's written by a person.
Of course, it's not always easy, but TypeScript consistently indents, accounts for multiple lines of code, and also positions comments written around the code.

If the type check error If given, What?
hello.tsI'll rewrite .

// @noErrors
// 아래는 실무 수준에서 범용적으로 쓰이는 환영 함수입니다
function greet(person, date) {
  console.log(`Hello ${person}, today is ${date}!`);
}

greet("Brendan");

Here tsc hello.tsNote that if you run again, you will get an error on the command line!

Expected 2 arguments, but got 1.

TypeScript is a greet I'm telling you that I forgot to pass arguments to the function, and that's actually the case.
So far, we've only written standard JavaScript, and we've still been able to find problems with our code through type checks.
Thanks, TypeScript!

Causing errors

I don't know if you've noticed from the previous example, hello.js The contents of the file have been modified again.
When you open the file, you can see that it is substantially the same as the code file used as the input.
Looking at our code tscIt may seem somewhat surprised that it caused an error, but this behavior is based on one of the core values of TypeScript. It's right, in most cases You The idea is that you know better than TypeScript.

As mentioned earlier, type checking for code limits the behavior that a program can perform. Therefore, there are some trade-offs and compromises in the range of actions that type checks allow or limit.
In most cases, the problem does not occur, but there are scenarios where type checks are intrusive.
For example, consider a type checking error while migrating code written in JavaScript to TypeScript.
Eventually, we'll fix the code to pass the type check, but in fact, the original JavaScript code was already working fine!
Why should I stop running code because of converting to TypeScript?

So TypeScript doesn't disturb you.
Of course, you may want to respond more defensively to mistakes over time, and make TypeScript work more strictly.
In this case, --noEmitOnError You can use the compiler option.
hello.ts After modifying the file, use the flag options above to tscTry to run .

tsc --noEmitOnError hello.ts

hello.jsis not modified.

Explicit type

So far, it's still person or datedid not tell us what it was.
Modify the code to personTwo stringAnd dateprice Date let them know that it should be an object.
In addition dateof toDateString() I'll use a method.

function greet(person: string, date: Date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}

Just as we personand dateas opposed to _Type notation_to do this greetthe types of values that can be used together when called.
The signature is "greetis string of the type personand Date of the type datehave a " can be interpreted.

If this is the case, TypeScript will be able to tell you if we use the function incorrectly.
For example...

// @errors: 2345
function greet(person: string, date: Date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}

greet("Maddison", Date());

Yes?
TypeScript reported an error with the second case, so why?

Perhaps surprisingly, in JavaScript Date()If you call stringreturns .
While new Date()Use Date You must create a type so that you can return the results you initially expected.

Anyway, this error can be fixed very quickly.

function greet(person: string, date: Date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}

greet("Maddison", new Date());

Remember that you don't always have to write explicit type notation.
In many cases, TypeScript inferred (or "figure it out").

let msg = "hello there!";
//  ^?

msgprice string Even if you didn't tell TypeScript that you had a type, TypeScript can figure it out.
This is the basic function, and if the type system can somehow figure out the correct type, it is best not to have a small number of type notations.

Note: The windboat in the code above is what appears on the mouse hover screen in that variable when you write it in the editor.

Erased type

Functions you wrote earlier greeta tscto see what happens when you get javascript output.

// @showEmit
// @target: es5
function greet(person: string, date: Date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}

greet("Maddison", new Date());

You can see two things here.

  1. personand date The indessation no longer has type notation.
  2. "Template String" - Backtic (` sentences written using characters) - is a connection operator (+) to a generic string consisting of .

For the second item, let's do more in detail and focus on the first one first.
Type notation is not part of JavaScript (or, strictly speaking, ECMAScript), so there is currently no browser or runtime that can run TypeScript without modification.
This is why, among other things, you need a compiler when you want to use TypeScript. You need a way to remove or convert TypeScript-only code so that it can be run.
Most TypeScript-only code is removed, and similarly type notation is completely erased.

Remember: Type notation does not modify the runtime behavior of the program at all.

Down-leveling

Another difference mentioned earlier is that the template string is

`Hello ${person}, today is ${date.toDateString()}!`;

it has been re-created with the following:

"Hello " + person + ", today is " + date.toDateString() + "!";

Why did this happen?

Template strings are ECMAScript 2015 (a.k.a. ECMAScript 6, ES2015, ES6, and so on. Don't ask more.) is a feature that appeared in the version of ECMAScript.
TypeScript rewrites the code for the new version of ECMAScript into older versions, such as ECMAScript 3 or ECMAScript 5.
The process of changing a new or "parent" version of ECMAScript to an old or "child" version _Down-leveling_it's also called a "10-0" (198

The default behavior of TypeScript is to target a very old ecmascript called ES3.
--target You can also set a flag to convert a more recent version to a target.
--target es2015Running can cause TypeScript to target ECMAScript 2015, which means that ecmascript 2015 is converted to run as long as it is a supported runtime.
consequently tsc --target es2015 input.tsYou will get the following output when you run .

function greet(person, date) {
  console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}
greet("Maddison", new Date());

The default for the target version is ES3, but many existing browsers support ES2015.
So if maintaining compatibility with a particular old version of a browser isn't a major issue, in most cases you can target the compiler with confidence that ES2015 or more is the case.

Strict

The purpose of using TypeScript's type checker varies from user to user.
While someone maintains a loose level of performing type checks on only part of the program, they may want to take full advantage of its useful programming tools.
This is the experience you want to provide by default when using TypeScript. Type checking is optional, type inference is made on the most lenient basis, and null/undefined No checks are made on the value.
These basic experiences are done in a direction that does not interfere with the development experience. In the event of a previously mentioned error, tscis similar to how it handles errors.
If you're migrating from traditional JavaScript, this is a good place to get started.

On the other, many users prefer typeScript to perform type checks as much as possible. This is also why TypeScript provides stricter settings.
These strictness settings allow you to make a static type checker as if it were a switch-level device (simply whether code checking was done or not) to a device that is as close to the dial as if it were.
The farther you turn the dial, the more TypeScript will check.
This will give you a little more work to do, but it's definitely worth it when you take a long time, and you'll be able to use more thorough inspections and precise tooling.
If possible, you should always enable stricture in your new code.

TypeScript has several type check severity flags that can be turned on and off, and all future example code is written with all flags enabled unless other than a description.
In cli --strict Set a flag or tsconfig.jsonat "strict": trueyou will activate all flags at the same time, but you can also drag each flag individually.
The two main options that you must know are: noImplicitAnyand strictNullChecksIs.

noImplicitAny

In some cases, TypeScript does not deduce the type of value, but anyplease remember that it is considered to be.
This is not the worst case. Anyway, a type anyis also a matter of course in typical JavaScript.

but anyoften makes the reason for using TypeScript colorless in the first place.
The more specific the type is in your program, the more validation and tool features you can use, which means you'll encounter fewer bugs in your code.
noImplicitAny When you enable a flag, the type anyimplicitly causes errors for inferred variables.

strictNullChecks

nulland undefinedThe default behavior is that values such as can be assigned to values of other types.
This makes writing code easier, nulland undefinedis the cause of the world's many bugs. One may Million Dollar MistakeIt's also called!
strictNullChecks The flag is nulland undefinedmore explicitly. null and undefined Processing Forgot from having to worry whether or not we Free him. I'm not a good man.

Generated by 🚫 dangerJS against 1c09750

@yeonjuan YeonJuan (yeonjuan) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

cadenzah (@cadenzah) 잘 읽히게 번역된 것 같습니다. 감사합니다 :) 띄어쓰기랑 오타 몇 개를 발견해서 제안 남겼습니다.

Comment thread docs/documentation/ko/handbook-v2/Basics.md Outdated
Comment thread docs/documentation/ko/handbook-v2/Basics.md Outdated
Comment thread docs/documentation/ko/handbook-v2/Basics.md Outdated
Comment thread docs/documentation/ko/handbook-v2/Basics.md Outdated
Comment thread docs/documentation/ko/handbook-v2/Basics.md Outdated
Comment thread docs/documentation/ko/handbook-v2/Basics.md Outdated
Comment thread docs/documentation/ko/handbook-v2/Basics.md Outdated
Comment thread docs/documentation/ko/handbook-v2/Basics.md Outdated
Comment thread docs/documentation/ko/handbook-v2/Basics.md Outdated
Comment thread docs/documentation/ko/handbook-v2/Basics.md Outdated
Co-authored-by: YeonJuan <yeonjuan93@naver.com>
@cadenzah

Copy link
Copy Markdown
Contributor Author

cadenzah (@cadenzah) 잘 읽히게 번역된 것 같습니다. 감사합니다 :) 띄어쓰기랑 오타 몇 개를 발견해서 제안 남겼습니다.

YeonJuan (@yeonjuan) 검토 감사드립니다. 다음 번에는 꼭 맞춤법 검사기를 한번 돌린 뒤에 PR을 올려야겠습니다 😅

@yeonjuan

Copy link
Copy Markdown
Contributor

cadenzah (@cadenzah) 수정 감사합니다 :)

@yeonjuan

Copy link
Copy Markdown
Contributor

LGTM

@github-actions
github-actions Bot merged commit 9f0bad2 into microsoft:main May 14, 2021
@github-actions

Copy link
Copy Markdown
Contributor

Merging because YeonJuan (@yeonjuan) is a code-owner of all the changes - thanks!

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