タイプスクリプトの使用
1.タイプ別
1) string, number, boolean
const name: string = "sj"
const age: number = 26
const hasGirlFriend: boolean = false
2) array
①資料の種類が同じ場合
const nickname: string[] = ["a","b","c","d"]
const age: number[] = [1,2,3,4]
②資料型が多い場合
const nickname: (string|number)[] = ["a",1,"b",2]
const age: (number|boolean)[] = [1,true,2,false]
3) object
const myInfo: {
name: string
age: number
hasGirlFriend: boolean
}= {
name: "sj",
age: 26,
hasGirlFriend: false
}
4) function
function getMyNickname(name: string):string{
const nickname = `cool ${name}`
return nickname
}
const getMyNickname = (name?: string):string => {
const nickname = `cool ${name}`
return nickname
}
const name: string = "sj"
const age: number = 26
const hasGirlFriend: boolean = false
const nickname: string[] = ["a","b","c","d"]
const age: number[] = [1,2,3,4]
const nickname: (string|number)[] = ["a",1,"b",2]
const age: (number|boolean)[] = [1,true,2,false]
const myInfo: {
name: string
age: number
hasGirlFriend: boolean
}= {
name: "sj",
age: 26,
hasGirlFriend: false
}
function getMyNickname(name: string):string{
const nickname = `cool ${name}`
return nickname
}
const getMyNickname = (name?: string):string => {
const nickname = `cool ${name}`
return nickname
}
5) Union
const age: string|number = 26 // or "26"
6)小整理
2.タイプ変数(type alias)
type AgeType = string | number
const age: AgeType = 26 // or "26"
1)宣言関数はタイプ変数を許可しない
type GetMyNickNameType = (name:string|number) => string;
function getMyNickname(name){
const nickname = `cool ${name}`
return nickname
}
// 선언 함수에서는 타입변수 사용불가하더라
const getMyNickname:GetMyNickNameType = function(name){
const nickname = `cool ${name}`
return nickname
}
const getMyNickname:GetMyNickNameType = (name) => {
const nickname = `cool ${name}`
return nickname
}
2)対象
① [key: string]
type MemberType = {
[key: string]: string
}
const member :MemberType = {
lastName: "choi",
FirstName: "sj",
hobby: "walk",
job: "student"
~~~ // value가 string이기만 하면 된다.
}
②オブジェクトはタイプではなくインタフェースが好き
interface IStudent{
name: string
}
interface ITeacher extends IStudent{
subject: string
}
const student: IStudent = {name: "choi"}
const teacher: ITeacher = {name: "park", subject: "korean"}
interface IStudent{
name: string
}
interface IStudent{
age: number
}
IStudent // === {name:string, age:number}
③readonly(推奨文字)
type FriendsName = {
readonly name: string
}
const friends :FriendsName = {
name: "park"
}
Reference
この問題について(タイプスクリプトの使用), 我々は、より多くの情報をここで見つけました https://velog.io/@db970406/타입스크립트-사용テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol