interface Room {
numDoors: number;
ceilingHeightFt: number;
}
const r : Room = {
numDoors: 1,
ceilingHeightFt: 10,
elephant: 'present',
//~~~~~~~~~~~~~~~~~~~~ 개체 리터럴은 알려진 속성만 지정할 수 있으며
// 'Room' 형식에 'elephant'가 없습니다.
}
const obj = {
numDoors: 1,
ceilingHeightFt: 10,
elephant: 'present'
};
const r : Room = obj; // 정상
function rollDice1(sides: number): number {/*...*/} // 문장
const rollDice2 = function(sides: number):number {/*...*/} // 표현식
const rollDice3 = (sides: number) : number => {/*...*/} // 표현식
type DiceRollFn = (sides: number) => number;
const rollDice: DiceRollFn = sides => {/*...*/}
const checkedFetch : typeof fetch = async (input,init) => {
const response = await fetch(input,init);
if(!response.ok){
throw new Error('Request failed: '+response.status);
}
return response;
}
타입스크립트에서 명명된 타입을 정의하는 방법은 두 가지가 있다.
type TState = {
name : string;
capital: string;
}
interface IState {
name : string;
capital : string;
}
const errorIState : IState = {
name:'test',
capital: 'capital',
population: 500_000
// ~~~~~~~~~~~~~~~~~~ 개체 리터럴은 알려진 속성만 지정할 수 있으며 IState 형식에 population 속성이 없습니다.
}
const errorTState : TState = {
name:'test',
capital: 'capital',
population: 500_000
// ~~~~~~~~~~~~~~~~~~ 개체 리터럴은 알려진 속성만 지정할 수 있으며 TState 형식에 population 속성이 없습니다.
}
type TDict = {[key:string]:string};
interface IDict {
[key:string]:string;
}
type TFn = (x:number) => string;
interface IFn {
(x:number):string;
}
const toStrT:TFn = x => '' + x;
const toStrI:IFn = x => '' + x;
type TPair<T> = {
first : T;
second: T;
}
interface IPair<T>{
first: T;
second: T;
}
type AorB = 'a' | 'b';
interface IState {
name: string;
capital: string;
}
interface IState {
population: number;
}
const wyoming: IState = {
name: 'Wyoming',
capital: 'Cheyenne',
population:500_000
}; // 정상
interface Person {
firstName : string,
lastName : string
}
interface PersonWithBirthDate extends Person {
birth : Date;
}
type PersonWithBirthDate = Person & { birth:Date };
type Pick<T,K> = { [k in K] : T[k] };
//example
type TopNavState = Pick<State, 'userId' | 'pageTitle' | 'recentFiles' >;
interface Options {
width: number;
height: number;
color: string;
label: string;
}
interface OptionsUpdate {
width?: number;
height?: number;
color?: string;
label?: string;
}
class UIWidget {
constructor(init:Options){/*...*/}
update(options:OptionsUpdate){/*...*/}
}
class UIWidget {
constructor(init:Options){/*...*/}
update(options:Partial<Options>){/*...*/}
}
type Rocket = {[property:string] : string};
cosnt rocket: Rocket = {
name:'Falcon 9',
variant: 'v1.0',
thrust: '4,940 kN',
}
[property:string] :string 이 인덱스 시그니처이며 다음 세 가지 의미를 가지고 있다.
키의 이름 :키의 위치만 표시하는 용도이다. 타입 체커에서는 사용하지 않는다.
키의 타입 :string이나 number 또는 symbol의 조합이어야 하지만, 보통은 string을 사용한다.
값의 타입 :어떤 것이든 될 수 있다.
type Vec3D = Record<'x' | 'y' | 'z', number>;
//Type Vec3D = {
// x : number;
// y : number;
// z : number;
//}