타입스크립트 강의 정리
Joy of Code
function returnString(name : string) : string {
return name + "string";
}
Array<Type>
문법이나,Type[]
문법이 있음const foo: Array<string> = ['foo1', 'foo2', 'foo3']
const foo: string[] = ['foo1', 'foo2', 'foo3']
function addArray(target: string[], name: string): string[] {
return target.push(name);
}
const addArray = (target: string[], name: string): string[] => {
return target.push(name);
}
?
operatorfunction logFunc(info: string, code?: string){
console.log({info, code})
}
const inferedEx = {
name: 'meme'
}
const explicitEx: {name: string} = {
name: 'meme'
}
const optionalEx: {id?: string, name: string} = {
name: 'meme'
} // 'id' is optional
type Person = {id: number; name: string; mbti: string}
const person_foo: Person[] = [
{
id: 1,
name: 'meme',
mbti: 'INFJ
}
]
type LogPerson = (name: string) => void
// named function expression
const logMemeIns : LogPerson = function logMeme(name) {
console.log(name);
}
// anonymous function expression
const logMeme: LogPerson = function(name) {
console.log(name);
}
// anonymous arrow function expression
const logMeme: LogPerson = (name) => {
console.log(name);
}
Interface는 Type Aliases의 다른 방식임
Interface를 사용함에 있어, 주의해야 할 점은 이미 시스템에 의해 정의된(eg, Window) 타입의 경우 사용하면 예상치 못한 결과를 얻을 수 있음.
interface Person {
id: number;
name: string;
description?: string;
callback(): void
}
const personMeme: Person = {
id: 1,
name: 'Meme',
callback() {
console.log('My name is meme');
}
For the most part, you can choose based on personal preference, and TypeScript will tell you if it needs something to be the other kind of declaration. If you would like a heuristic, use interface until you need to use features from type. - TypeScript Handbook
&
와 같음)interface Person {
id: number;
name: string;
};
interface Human extends Person {
race: 'white';
}
const John: Human = { // satisfies
id: 1,
name: John,
race: 'white
}
function logPersons(names: string[] | string) {
console.log(names);
}