프로퍼티에 적으면 프로퍼티 데코레이터, 파라미터 옆이면 파라미터 데코레이터가 된다고 한다.
@makeGender
class Person{}
class Person{
@validate title : string
}
// typeof Person안하고 Person만 적으면 인스턴스가 되버려서 꼭 typeof Person해야한다.
function makeGender(target: typeof Person){
// 원본을 인자로 받아서 새로운 것을 extends 시켜서 내보낸다.
return class extends target{
//...
}
}
@makeGender
class Person{
//....
}
@makeGender
class Person2{
//....
}
데코레이터의 각각의 위치에 따라서 매개변수가 달라진다고 한다.
3번째 인자 값이 달라진다.
// 클래스 데코레이터
function readonly(target: any, key: any, descriptor: propertyDescriptor){
//....
}
// 파라미터 데코레이터
function readonly(target: any, key: any, index: number){
//....
}
Q&A 타입스크립트는 왜써요?
노드로 개발할 경우 서버가 죽는 경우가 생긴다.
보통어이없는 실수가 대부분이다.
타입스크립트는 코드 작성 시 에디터에서 한번 걸러주고 빌드시 두번 걸러줘서 안정성이 올라갈 수 있다.
자바스크립트는 런타입에서 오류가 나야 알 수 있다.
퍼포먼스가 좋아지는 일은 없다.
안좋아지는 일도 없다 빌드하는 시간이 걸리기는 하지만 컴파일된 코드를 런타임에서 실행하기 때문에 퍼포먼스에는 이상이 없다.
undefined는 undefined의 타입을 가지고 있다 void 0의 타입도 undefined이다.
const n = null;
const n = undefined;
const n = void 0;
함수에서 사용하기
함수에서 타입스크립트는 변수, 매개변수, 리턴 값에 타입을 붙일 수 있다.
// (매개변수) : 리턴 값에 대한 타입
function f(a: number, b: number): number | string {
return a + b;
}
리턴 값이 없는 함수는 return undefined가 생략된 것이지만 이럴경우 타입을 void로 적으면 된다.
undefined로 작성하면 에러가 난다.
function f(a: number, b: number): void {
console.log(a, b);
}
고차함수
함수가 고차함수를 리턴하는 경우 리턴되는 값의 타입을 작성하면된다.
함수의 타입은 리턴 값의 타입 자리에 적어준다.
// 함수 자체를 타입으로 쓸때
// (c: string) => number 함수 파라미터의 타입값과 함께 리턴 값을 적어줘야한다.
function f(a: number, b: number): (c: string) => number {
return(c: string) => {
return c;
}
}
// 함수를 선언할때
function f(p: number): number{
// ....
}
/**
* Utility functions for the foo package.
* @module foo/util
* @license Apache-2.0
*/
예제2
독립라이센스가 있는 파일
/**
* @license
* Copyright (c) 2015 Example Corporation Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
출력화면
함수에 사용할 수 있는 주석
@this
해당 함수내부의 this가 참조하는 것을 표시
문법
// @this <namePath>
예제
/** @constructor */
function Greeter(name) {
setName.apply(this, name);
}
/** @this Greeter */
function setName(name) {
/** document me */
this.name = name;
}
출력화면
@constant (@const)
상수를 표시
문법
// @constant [<type> <name>]
예시
/**
* @constant
* @type {string}
* @default
*/
const RED = 'FF0000';
/** @constant {number} */
var ONE = 1;
@description (@desc)
설명을 표시
문법
// @description <some description>
예제
첫번째 줄일때에는 생략가능
/**
* Add two numbers.
* @param {number} a
* @param {number} b
* @returns {number}
*/
function add(a, b) {
return a + b;
}
예제2
첫번째 줄이 아닐때
/**
* @param {number} a
* @param {number} b
* @returns {number}
* @description Add two numbers.
*/
function add(a, b) {
return a + b;
}
/**
* @param {(string|string[])} [somebody=John Doe] - Somebody's name, or an array of names.
*/
function sayHello(somebody) {
if (!somebody) {
somebody = 'John Doe';
} else if (Array.isArray(somebody)) {
somebody = somebody.join(', ');
}
alert('Hello ' + somebody);
}
예제3
파라미터에 속성이 있을때
/**
* Assign the project to an employee.
* @param {Object} employee - The employee who is responsible for the project.
* @param {string} employee.name - The name of the employee.
* @param {string} employee.department - The employee's department.
*/
Project.prototype.assign = function(employee) {
// ...
};
예제4
파라미터가 배열, 속성이 있을경우
/**
* Assign the project to a list of employees.
* @param {Object[]} employees - The employees who are responsible for the project.
* @param {string} employees[].name - The name of an employee.
* @param {string} employees[].department - The employee's department.
*/
Project.prototype.assign = function(employees) {
// ...
};
출력화면
@requires
필요한 모듈이 있음을 표현
문법
// @requires <someModuleName>
예제
/**
* This class requires the modules {@link module:xyzcorp/helper} and
* {@link module:xyzcorp/helper.ShinyWidget#polish}.
* @class
* @requires module:xyzcorp/helper
* @requires xyzcorp/helper.ShinyWidget#polish
*/
function Widgetizer() {}
출력화면
@callback
콜백으로 받은 인자 및 반환 값에 대한 정보 제공
문법
// @callback <namepath>
예제
클래스 별
/**
* @class
*/
function Requester() {}
/**
* Send a request.
* @param {Requester~requestCallback} cb - The callback that handles the response.
*/
Requester.prototype.send = function(cb) {
// code
};
/**
* This callback is displayed as part of the Requester class.
* @callback Requester~requestCallback
* @param {number} responseCode
* @param {string} responseMessage
*/
예제2
글로벌
/**
* @class
*/
function Requester() {}
/**
* Send a request.
* @param {requestCallback} cb - The callback that handles the response.
*/
Requester.prototype.send = function(cb) {
// code
};
/**
* This callback is displayed as a global member.
* @callback requestCallback
* @param {number} responseCode
* @param {string} responseMessage
*/
@todo
해야하거나, 완료해야할 작업이 필요할때 표시
단일 주석에 두번 사용 금지
문법
// @todo text describing thing to do.
예제
/**
* @todo Write the documentation.
* @todo Implement this function.
*/
function foo() {
// write me
}
출력화면
@return (@returns)
함수가 반환하는 값을 표시
문법
// @returns [{type}] [description]
예제
/**
* Returns the sum of a and b
* @param {number} a
* @param {number} b
* @returns {number} Sum of a and b
*/
function sum(a, b) {
return a + b;
}
출력화면
@see
연관성 있는 문서나 리소스 참조함을 표시
{@link} 와 같이 사용 가능
문법
// @see <namepath>
// @see <text>
예제
/**
* Both of these will link to the bar function.
* @see {@link bar}
* @see bar
*/
function foo() {}
// Use the inline {@link} tag to include a link within a free-form description.
/**
* @see {@link foo} for further information.
* @see {@link http://github.com|GitHub}
*/
function bar() {}
출력화면
@link ({@linkcode}, {@linkplain})
namepath 또는 url에 대한 링크 생성
문법
// {@link namepathOrURL}
// [link text]{@link namepathOrURL}
// {@link namepathOrURL|link text}
// {@link namepathOrURL link text (after the first space)}
예제
/*
** See {@link MyClass} and [MyClass's foo property]{@link MyClass#foo}.
* Also, check out {@link http://www.google.com|Google} and
* {@link https://github.com GitHub}.
*/
function myFunction() {}
@since
클래스, 메서드 등이 특정 버전에서 추가되었을때 사용
문법
// @since <versionDescription>
예제
/**
* Provides access to user information.
* @since 1.0.1
*/
function UserRecord() {}
/**
* Solves equations of the form a * x = b
* @example
* // returns 2
* @example <caption>Example usage of method1.</caption>
* // returns 2
* globalNS.method1(5, 10);
* @returns {Number} Returns the value of x for the equation.
*/
globalNS.method1 = function (a, b) {
return b / a;
};
/**
* My namespace.
* @namespace
*/
var MyNamespace = {
/** documented as MyNamespace.foo */
foo: function() {},
/** documented as MyNamespace.bar */
bar: 1
};
예제2
/**
* A namespace.
* @namespace MyNamespace
*/
/**
* A function in MyNamespace (MyNamespace.myFunction).
* @function myFunction
* @memberof MyNamespace
*/
예제3
/** @namespace window */
/**
* Shorthand for the alert function.
* Refer to it as {@link window."!"} (note the double quotes).
*/
window["!"] = function(msg) {
alert(msg);
};
@inner
네임스페이스 태그의 부모-자녀 참조
예제
/** @namespace */
var MyNamespace = {
/**
* foo is now MyNamespace~foo rather than MyNamespace.foo.
* @inner
*/
foo: 1
};
@alias
네임스페이스 태그의 멤버 참조처리
내부 함수 내에 클래스 정의할 때 유용하다
예제
/** @namespace */
var Apple = {};(function(ns) {
/**
* @namespace
* @alias Apple.Core
*/
var core = {};
/** Documented as Apple.Core.seed */
core.seed = function() {};
ns.Core = core;
})(Apple);
클래스를 설명하는 주석
class 키워드를 사용했거나 생성자를 통해 개발한 경우 해당할 수 있습니다.
@class (@constructor)
함수 생성자로 표시
문법
// @class [<type> <name>]
예제
/**
* Creates a new Person.
* @class
*/
function Person(){}
var p = new Person();
출력화면
@classdesc
함수 생성자 설명
@class가 선언되어있어야 한다.
문법
// @classdesc <some description>
예제
/**
* This is a description of the MyClass constructor function.
* @class
* @classdesc This is a description of the MyClass class.
*/
function MyClass() {}
/** @class */
var Person = makeClass(
/** @lends Person */
{
/**
* Create a `Person` instance.
* @param {string} name - The person's name.
*/
initialize: function(name) {
this.name = name;
},
/**
* Say something.
* @param {string} message - The message to say.
* @returns {string} The complete message.
*/
say: function(message) {
return this.name + " says: " + message;
}
}
);
@abstract (@virtual)
상속하는 객체에서 재정의하는 멤버 식별(오버라이딩 객체)
예제
/**
* Generic dairy product.
* @constructor
*/
function DairyProduct() {}
/**
* Check whether the dairy product is solid at room temperature.
* @abstract
* @return {boolean}
*/
DairyProduct.prototype.isSolid = function() {
throw new Error('must be implemented by subclass!');
};
/**
* Cool, refreshing milk.
* @constructor
* @augments DairyProduct
*/
function Milk() {}
/**
* Check whether milk is solid at room temperature.
* @return {boolean} Always returns false.
*/
Milk.prototype.isSolid = function() {
return false;
};
출력화면
@augments (@extends)
클래스 기반이나 프로토타입 기반에서 상속을 나타내고 상위 객체를 추가함
문법
// @augments <namepath>
예제
단일상속
/**
* @constructor
*/
function Animal() {
/** Is this animal alive? */
this.alive = true;
}
/**
* @constructor
* @augments Animal
*/
function Duck() {}
Duck.prototype = new Animal();
예제2
다중 상속
/**
* Abstract class for things that can fly.
* @class
*/
function Flyable() {
this.canFly = true;
}
/** Take off. */
Flyable.prototype.takeOff = function() {
// ...
};
/**
* Abstract class representing a bird.
* @class
*/
function Bird(canFly) {
this.canFly = canFly;
}
/** Spread your wings and fly, if possible. */
Bird.prototype.takeOff = function() {
if (this.canFly) {
this._spreadWings()
._run()
._flapWings();
}
};
/**
* Class representing a duck.
* @class
* @augments Flyable
* @augments Bird
*/
function Duck() {} // Described in the docs as "Spread your wings and fly, if possible."
Duck.prototype.takeOff = function() {
// ...
};
주석 정리 후 모듈에 적용을 해봤는데, 아직 정확한 개념이 박히지 않아서 오래걸리는군요 ㅎㅎ..