let v1 = 123;
v1 = 'abc';
TypeScriptμμ μμ κ°μ΄ μ μΈ μ λ λ²μ§Έ v1μ νμ
μλ¬κ° λ°μν©λλ€.
μ΄λ 첫 λ²μ§Έ ν λΉ μ λ¬Έμμ΄μ΄ μλ μ«μκ° λ³μμ λ΄κ²ΌκΈ° λλ¬Έμ
λλ€.
μ΄λ₯Ό νμ
μΆλ‘ (type inference)μ΄λΌκ³ ν©λλ€.
λ κ°μ§ λͺ¨λ λ³μμ λ΄κΈ° μν΄μλ λ κ°μ§ νμ
μ λͺ
μν΄ μ£Όμ΄μΌ ν©λλ€.
let v1: number | string = 123;
v1 = 'abc';
any νμ
μ λͺ¨λ μ’
λ₯μ κ°μ νμ©ν©λλ€.
const values: number[] = [1, 2, 3];
const values: Array<number> = [1, 2, 3];
const data: [string, number] = [msg, size];
let value: any;
value = 123;
value = '123';
value = () => {};
enum Fruit {
Apple,
Banana,
Orange,
}
const v1: Fruit = Fruit.Apple;
const v2: Fruit.Apple | Fruit.Banana = Fruit.Banana;
μ΄κ±°ν νμ
μ κ°μ²΄μ΄κ³ , κ° μμλ κ°μΌλ‘ μ¬μ©λ μ μκ³ , νμ
μΌλ‘ μ¬μ©λ μλ μμ΅λλ€.
μμ μ΄κ²¨ν νμ
μ μ¬μ©ν κ²½μ° μ»΄νμΌ νμλ λ¨μ μμ§ μκ² λ©λλ€.
function getInfoText(name: string, age: number): string {
}
ν¨μ νμ
μ μ μνκΈ° μν΄μλ 맀κ°λ³μ νμ
κ³Ό λ°ν νμ
μ΄ νμν©λλ€.
μλ°μμμ μΈν°νμ΄μ€λ ν΄λμ€λ₯Ό ꡬννκΈ° μ μ νμν λ©μλλ₯Ό μ μνλ μ©λλ‘ μ¬μ©λ©λλ€.
TypeScriptμμλ μ’ λ λ€μν κΈ°λ₯μ κ°μ§κ³ μμ΅λλ€.
μλλ μΈν°νμ΄μ€λ‘ κ°μ²΄ νμ
μ μ μνλ κ²μ μμ보λλ‘ νκ² μ΅λλ€.
interface Person {
name: string;
age: number;
}
Person μΈν°νμ΄μ€μμ νλ μ΄μμ μμ± νμ
μ λ§μ‘±νμ§ λͺ»νλ©΄ νμ
μλ¬κ° λ°μν©λλ€.
μ ν μμ±μ μΆκ°νλ €λ©΄ ?
κΈ°νΈλ₯Ό μ¬μ©ν΄μΌ ν©λλ€.
μ½κΈ° μ μ©μ readonly
λ₯Ό μΆκ°ν©λλ€.
interface Person {
readonly name: string;
age?: number;
}
const p1: Person = {
name: 'mike',
birthday: '222-22-22',
}
function makeArray<T>(defaultValue: T, size: number): T[] {
const arr: T[] = [];
for(let i = 0; i < size; i++) {
arr.push(defaultValue);
}
return arr;
}
const arr1 = makeArray<number>(1, 10);
const arr2 = makeArray<string>('abc', 10);
const arr3 = makeArray('abc', 10);
μ λ€λ¦μ νμ
μ λ³΄κ° λμ μΌλ‘ κ²°μ λλ©°, κ°μ κ·μΉμ μ¬λ¬ νμ
μ μ μ©ν μ μμ΅λλ€.
import React from 'react';
interface Props {
name: string;
age?: number;
}
const MyComponent: React.FunctionComponent<Props> = function({ name, age = 23 }) {
return (
<>
<p>{name}</p>
<p>{age.substr(0)}</p>
</>
);
};
import React, { createRef } from 'react';
interface Props {
containerStyle: React.CSSProperties;
theme: string;
}
const defaultProps = {
theme: 'dark',
}
interface State {
name: string;
age: number | undefined;
}
class MyComponent extends React.Component<Props, State> {
state = {
name: 'mike',
age: undefined,
};
static defaultProps = defaultProps;
pRef = createRef<HTMLParagraphElement>();
onClick1 = (e: EventObject) => {
console.log(e.currentTarget.dataset['food']);
};
onClick2 = (e: React.MouseEvent<HTMLButtonElement>) => {
console.log(`${e.clientX}, ${e.clientY}`);
};
render() {
const { containerStyle, theme } = this.props;
const { name, age } = this.state;
return (
<div style={containerStyle}>
<p ref={this.pRef}>{name}</p>
<button data-foold="soup" onClick={this.onClick1}>λ²νΌ1</button>
<button onClick={this.onClick2}>λ²νΌ2</button>
</div>
)
}
}
https://overreacted.io/ko/how-are-function-components-different-from-classes/