[typescript] Type assertions, union type, literal type, alias
8501 ワード
Type Assertions
anyまたはunbownとして宣言して参照するときのブレークスルータイプ(タイプオーバーライド)
// (1) as
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length; // (*)
// (2) angle-bracket
let someValue: unknown = "this is a string";
let strLength: number = (<string>someValue).length; // (*)
Union Type
1つ以上のタイプを使用する場合(より柔軟)
function combine(input1: number | string, input2: number | string) {// (*)
let result;
if(typeof input1 === 'number' && typeof input2 === 'number') { // runtime type check
return input1 + input2;
} else {
return input1.toString() + input2.toString();
}
return result;
}
const combineAge = combine(21, 30);
const combineName = combine('Suyeon', 'Hanna');
Literal Type
It allows an exact value which a string, number, or boolean must have.
// string
function createElement(tagName: "img"): HTMLImageElement;
function createElement(tagName: "input"): HTMLInputElement;
function(reslut: 'img' | 'text') {
if(result === 'text') {
// ...
} else {
// ...
}
}
// number
interface MapConfig {
tileSize: 8 | 16 | 32;
}
setupMap({ tileSize: 16 });
// boolean
interface ValidationSuccess {
isValid: true;
};
Alias
Reusable custom type set.
type pet = 'cat' | 'dog';
type Combinable = string | number;
function combine(input1: Combinable, input2: Combinable){...}
Reference
この問題について([typescript] Type assertions, union type, literal type, alias), 我々は、より多くの情報をここで見つけました https://velog.io/@suyeonme/typescript-Type-assertions-union-type-literal-type-aliasテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol