Last active
June 4, 2024 15:10
-
-
Save KazmaArakaki/4efe3cad54c274332d9c44fa9a5404ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. TypeScriptで書く | |
type Person = { | |
favoriteColor: string; | |
name: string; | |
age: number; | |
}; | |
// 2. Overloadも書ける | |
function makePerson(favoriteColor: string, name: string, age: number): Person; | |
function makePerson(name: string, age: number): Person; | |
// 3. インデントは揃える | |
function makePerson(favoriteColorOrName: string, nameOrAge: string | number, age?: number): Person { | |
// 4. 早期リターンを心がける | |
if ((age !== undefined) && (typeof nameOrAge === "string")) { | |
return { | |
favoriteColor: favoriteColorOrName, | |
name: nameOrAge, | |
age, | |
}; | |
} | |
if ((age === undefined) && (typeof nameOrAge === "number")) { | |
return { | |
favoriteColor: "green", | |
name: favoriteColorOrName, | |
age: nameOrAge, | |
}; | |
} | |
throw new Error("unexpected use of function"); | |
}; | |
const person = makePerson("Joe", 18); | |
// 5. ログは見やすい形で出力する | |
console.log({ person }); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var makePerson = function(favoriteColor, name, age) { | |
if (arguments.length < 3) { | |
favoriteColor = "green"; | |
name = arguments[0]; | |
age = arguments[1]; | |
} | |
return { | |
name: name, | |
age: age, | |
favoriteColor: favoriteColor | |
}; | |
}; | |
var person = makePerson("Joe", 18); | |
console.log(JSON.stringify(person)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment