Type predicate
readonly
ν΄λΉ λ°°μ΄, κ°μ²΄λ₯Ό μμ ν μ μκ³ μ€μ§ μ½μ μλ§ μκ² ν¨.
λ°°μ΄μ νν λ°©λ²μ΄
string[]
,Array<string>
2κ°μ§ μ΄μ§λ§,readonly
λ₯Ό μ¬μ©ν λλstring[]
ννμλ§ κ°λ₯νλ€.
function printArray(fruits: readonly string[]) {}
| (Union Type)
a λλ b λλ c λλ dκ° μ¬ μ μλ€λ λ».
type Direction = 'left' | 'right' | 'up' | 'down';
& (Intersection type)
λͺ¨λ κ²μ λ€ ν©ν μλ―Έλ‘ μ¬μ© aλ bλ cλ dλ λ€ μμ΄μΌ νλ€λ
type Student = {
name: string;
score: number;
};
type Worker = {
empolyeeId: number;
work: () => void;
};
function internWork(person: Student & Worker) {
console.log(person.name, person.empolyeeId, person.work());
}
in
μ°νμ μλ νμ μ μμ±μ κ°μ§κ³ μλμ§ νμΈ
type SuccessState = {
response: {
body: string;
};
};
type FailState = {
reason: string;
};
type LoginState = SuccessState | FailState;
function printLoginState(state: LoginState) {
if ('response' in state) {
console.log(`π ${state.response.body}`);
} else {
console.log(`π ${state.reason}`);
}
}
as (Type Assertion)
νμ μ λͺ μμ μΌλ‘ μ§μ ν΄ μ€
function jsStrFunc(): any {
return 2;
}
const result = jsStrFunc();
console.log((result as string).length);
console.log((<string>result).length);
!
μ λμ μΌλ‘ κ°μ΄ μμμ νμ ν λ νν
function findNumbers(): number[] | undefined {
return undefined;
}
const numbers = findNumbers()!;
// or
numbers!.push(2);
is
Aκ° Bνμ μΈμ§ μλμ§ νμΈ
A is B // true or false
Last updated
Was this helpful?