-
Notifications
You must be signed in to change notification settings - Fork 131
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 - More on Functions.md #150
Conversation
Translation of More on Functions.mdtitle: More on Functions oneline: "Let's see how functions work in TypeScript."Whether it's a local function, a function loaded from another module, or a method of any class, a function is a fundamental component of any application. Function type expressionsThe simplest way to describe a function is to Function type expressions Is. function greeter(fn: (a: string) => void) {
fn("Hello, World");
}
function printToConsole(s: string) {
console.log(s);
}
greeter(printToConsole);
Of course, you can use type aliases to name types in functions. type GreetFunction = (a: string) => void;
function greeter(fn: GreetFunction) {
// ...
} Call SignatureIn JavaScript, functions can not only be called, but also have properties. type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
console.log(fn.description + " returned " + fn(6));
} This syntax is different from function type expressions. Between the parameter type and the type of the return value Configuration SignaturesJavaScript functions are type SomeObject = any;
// ---cut---
type SomeConstructor = {
new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
return new ctor("hello");
} JavaScript interface CallOrConstruct {
new (s: string): Date;
(n?: number): number;
} Generic functionsIt is common to write a function in a form where the input value is related to the type of the output value, or that the type of the two inputs is related to each other. function firstElement(arr: any[]) {
return arr[0];
} The function does its job, but unfortunately the return type In TypeScript, Generic Grammars are used to express the correlation between two values. function firstElement<Type>(arr: Type[]): Type | undefined {
return arr[0];
} Type Parameters declare function firstElement<Type>(arr: Type[]): Type | undefined;
// ---cut---
// s는 "string" 타입
const s = firstElement(["a", "b", "c"]);
// n은 "number" 타입
const n = firstElement([1, 2, 3]);
// u는 "undefined" 타입
const u = firstElement([]); InferenceIn this example, we have We can also use multiple type parameters. // prettier-ignore
function map<Input, Output>(arr: Input[], func: (arg: Input) => Output): Output[] {
return arr.map(func);
}
// 매개변수 'n'의 타입은 'string' 입니다.
// 'parsed'는 number[] 타입을 하고 있습니다.
const parsed = map(["1", "2", "3"], (n) => parseInt(n)); In this example, TypeScript is Type constraintsWe are all We have written generic functions that operate on types. Let's write a function that returns the longer of the two values. // @errors: 2345 2322
function longest<Type extends { length: number }>(a: Type, b: Type) {
if (a.length >= b.length) {
return a;
} else {
return b;
}
}
// longerArray 의 타입은 'number[]' 입니다'
const longerArray = longest([1, 2], [1, 2, 3]);
// longerString 의 타입은 'alice' | 'bob' 입니다.
const longerString = longest("alice", "bob");
// 에러! Number에는 'length' 프로퍼티가 없습니다.
const notOK = longest(10, 100); In this example, there are a few interesting things to note. We
In the end, as we want Working with restricted valuesThe following are common mistakes to make when using generic type constraints: // @errors: 2322
function minimumLength<Type extends { length: number }>(
obj: Type,
minimum: number
): Type {
if (obj.length >= minimum) {
return obj;
} else {
return { length: minimum };
}
} This function appears to have no problems. declare function minimumLength<Type extends { length: number }>(
obj: Type,
minimum: number
): Type;
// ---cut---
// 'arr' gets value { length: 6 }
const arr = minimumLength([1, 2, 3], 6);
// 여기서 배열은 'slice' 메서드를 가지고 있지만
// 반환된 객체는 그렇지 않기에 에러가 발생합니다!
console.log(arr.slice(0)); Specifying Type ArgumentsTypeScript usually infers the intended type from generic calls, but this is not always the case. function combine<Type>(arr1: Type[], arr2: Type[]): Type[] {
return arr1.concat(arr2);
} In general, it would be wrong to call that function with an unpaired array. // @errors: 2322
declare function combine<Type>(arr1: Type[], arr2: Type[]): Type[];
// ---cut---
const arr = combine([1, 2, 3], ["hello"]); If you intended something like this, you can manually declare function combine<Type>(arr1: Type[], arr2: Type[]): Type[];
// ---cut---
const arr = combine<string | number>([1, 2, 3], ["hello"]); Guidelines for writing good generic functionsWriting generic functions can be fun, and using type parameters can be easy. Pressing Type ParametersHere's how to write two functions that look similar. function firstElement1<Type>(arr: Type[]) {
return arr[0];
}
function firstElement2<Type extends any[]>(arr: Type) {
return arr[0];
}
// a: number (good)
const a = firstElement1([1, 2, 3]);
// b: any (bad)
const b = firstElement2([1, 2, 3]); At first glance, it may look the same,
Using fewer type parametersHere is another pair of similar functions: function filter1<Type>(arr: Type[], func: (arg: Type) => boolean): Type[] {
return arr.filter(func);
}
function filter2<Type, Func extends (arg: Type) => boolean>(
arr: Type[],
func: Func
): Type[] {
return arr.filter(func);
} We are Do not associate two values Type Parameters
The type parameter must appear twice.Sometimes we overlook the fact that functions may not need generics. function greet<Str extends string>(s: Str) {
console.log("Hello, " + s);
}
greet("world"); We could have easily written a simple version. function greet(s: string) {
console.log("Hello, " + s);
} The type parameter is _Associating multiple value types_Please remember to use it for the purpose of doing so.
Optional ParametersFunctions used in JavaScript often take a variable number of arguments. function f(n: number) {
console.log(n.toFixed()); // 0 arguments
console.log(n.toFixed(3)); // 1 argument
} In TypeScript, we can select the parameters function f(x?: number) {
// ...
}
f(); // OK
f(10); // OK If the type of the parameter is You can use the parameters _Default_We can also provide it. function f(x = 10) {
// ...
} now declare function f(x?: number): void;
// cut
// All OK
f();
f(10);
f(undefined); Optional parameters in callback functionsOnce you know about optional parameters and function type expressions, it's easy to make the following mistakes when writing a function that invokes a callback: function myForEach(arr: any[], callback: (arg: any, index?: number) => void) {
for (let i = 0; i < arr.length; i++) {
callback(arr[i], i);
}
} People // @errors: 2532
declare function myForEach(
arr: any[],
callback: (arg: any, index?: number) => void
): void;
// ---cut---
myForEach([1, 2, 3], (a) => console.log(a));
myForEach([1, 2, 3], (a, i) => console.log(a, i)); indeed What this means is that // @errors: 2532
function myForEach(arr: any[], callback: (arg: any, index?: number) => void) {
for (let i = 0; i < arr.length; i++) {
// 오늘은 index를 제공하고 싶지 않아
callback(arr[i]);
}
} Eventually, TypeScript forces these semantics and throws an error that wouldn't actually happen. // @errors: 2532
declare function myForEach(
arr: any[],
callback: (arg: any, index?: number) => void
): void;
// ---cut---
myForEach([1, 2, 3], (a, i) => {
console.log(i.toFixed());
}); In JavaScript, if it is called by passing more arguments than specified as a parameter, the remaining arguments are simply ignored.
Function overloadSome JavaScript functions can be called with a variety of argument counts, types. In TypeScript, we have functions that can be called in different ways. _Overlord Signature_can be described by writing. // @errors: 2575
function makeDate(timestamp: number): Date;
function makeDate(m: number, d: number, y: number): Date;
function makeDate(mOrTimestamp: number, d?: number, y?: number): Date {
if (d !== undefined && y !== undefined) {
return new Date(y, mOrTimestamp, d);
} else {
return new Date(mOrTimestamp);
}
}
const d1 = makeDate(12345678);
const d2 = makeDate(5, 5, 5);
const d3 = makeDate(1, 3); In this example, we have created two overloads. One receives one argument, and the other receives three arguments. Then, we wrote a function implementation with compatible signatures. Overlord Signatures and Implementation SignaturesThis is a common source of confusion. // @errors: 2554
function fn(x: string): void;
function fn() {
// ...
}
// 0개의 인자로 호출하기를 예상했음
fn(); Again, the signature used to create the function body is "invisible" from the outside.
In addition, the implementation signature is an overloaded signature and Must be compatible The. // @errors: 2394
function fn(x: boolean): void;
// 인수 타입이 옳지 않습니다.
function fn(x: string): void;
function fn(x: boolean) {} // @errors: 2394
function fn(x: string): string;
// 반환 타입이 옳지 않습니다.
function fn(x: number): boolean;
function fn(x: string | number) {
return "oops";
} Writing good overloadsAs with generics, there are some guidelines to follow when writing function overloads. Consider a function that returns the length of a string or array. function len(s: string): number;
function len(arr: any[]): number;
function len(x: any) {
return x.length;
} This function is fine. We can call this function via string or array. // @errors: 2769
declare function len(s: string): number;
declare function len(arr: any[]): number;
// ---cut---
len(""); // OK
len([0]); // OK
len(Math.random() > 0.5 ? "hello" : [0]); Since both overloads have the same number of arguments and the same return type, we can write the following in the form of an unoverloaded function: function len(x: any[] | string) {
return x.length;
} Much better!
Within a function
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@kasterra 리뷰가 늦었습니다. 죄송합니다. 맞춤법, 띄어쓰기, 일부 부자연스러운 문장들에 코멘트 남겼습니다. 작업해 주셔서 감사합니다.
LGTM |
Merging because @yeonjuan is a code-owner of all the changes - thanks! |
리뷰 부탁드립니다.
@yeonjuan @bumkeyy