-
Notifications
You must be signed in to change notification settings - Fork 130
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
Conversation
Translation of Everyday Types.mdtitle: Everyday Types oneline: "primitive types of language."This chapter covers the most common types found in JavaScript code and explains how they are described in TypeScript. Types are much more diverse than just typewriting. _location_may appear in Let's start by revisiting some of the most basic and common types when writing JavaScript or TypeScript code. Primitive types:
|
인터페이스 |
타입 |
---|---|
인터페이스 확장하기
|
교집합을 통하여 타입 확장하기
|
기존의 인터페이스에 새 필드를 추가하기
|
타입은 생성된 뒤에는 달라질 수 없다
|
We'll learn more about the above concepts in later chapters, so don't worry if you don't understand them now.
- In TypeScript 4.2 and earlier, the type alias name is displayed in the error message and, sometimes appearing on behalf of an equivalent anonymous type (this may or may not be desirable in some cases). The interface always appears in the error message by name.
- Type aliases are it cannot be included in a declaration merge but it can contain interfaces.
- The interface is It is only used to declare the shape of an object, not to alias an existing primitive type.
- The name of the interface is Always as it is An error message appears. However, this means that only Only when the interface is used as a name in code.
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 interface
When problems occur after using type
Please use
Type assertion
Sometimes you know better information about the type of a value than TypeScript.
For example, in code: document.getElementById
If TypeScript is used, HTMLElement
During _something_is returned, whereas you can always use the ID used on the page HTMLCanvasElement
may 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, ornull
will 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
string
and number
In 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. var
and let
You can change the types of values that can be stored in all variables. const
This 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, true
and false
Is.
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 0
In the field that was 1
TypeScript does not consider it an error.
To put it another way, obj.counter
The 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.method
The string
Not inferred as, "GET"
It is not inferred from. req
The time of creation of and handleRequest
Code evaluation can occur at any time between the calls of req.method
at "GUESS"
, so TypeScript determines that the above code is in error.
There are two ways to resolve these cases:
-
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.method
Always 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.method
price"GET"
as a value." -
as const
to 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 const
It works similarly to , for all properties of that object. string
or number
Ensures that values of literal types that are not more general types such as are assigned to them.
null
and undefined
In JavaScript, there are two kinds of raw values, one that points to an empty value or an uninitialized value. straight null
and undefined
Is.
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.
strictNullChecks
is not set.
strictNullChecks
price If it is not set, what value null
or undefined
Even if it can be, you can approach the value as usual, null
and undefined
can 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
strictNullChecks
price 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 null
You 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. null
and undefined
Provides a special syntax to remove the .
After the expression !
, the value of which is null
or undefined
is 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 undefined
price 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 bigint
Is.
// @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
symbol
is 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 .
수정 감사합니다! |
LGTM |
Merging because @bumkeyy is a code-owner of all the changes - thanks! |
"Here's an example", "아래는 그 예시입니다" same meaning
옵셔널 프로퍼티� => 옵셔널 프로퍼티