From e5374d79a0a2f1f6b8c6fa0b89d9ed08f09f7908 Mon Sep 17 00:00:00 2001 From: Fendo181 Date: Thu, 29 May 2025 23:19:26 +0900 Subject: [PATCH 1/6] add: sum.ts --- study/typescript/02_grammer/sum.js | 4 ++++ study/typescript/02_grammer/sum.ts | 5 +++++ 2 files changed, 9 insertions(+) create mode 100644 study/typescript/02_grammer/sum.js create mode 100644 study/typescript/02_grammer/sum.ts diff --git a/study/typescript/02_grammer/sum.js b/study/typescript/02_grammer/sum.js new file mode 100644 index 0000000..a6ca085 --- /dev/null +++ b/study/typescript/02_grammer/sum.js @@ -0,0 +1,4 @@ +function sum(a, b) { + return a + b; +} +console.log(sum(2, 3)); // 5 diff --git a/study/typescript/02_grammer/sum.ts b/study/typescript/02_grammer/sum.ts new file mode 100644 index 0000000..eab416a --- /dev/null +++ b/study/typescript/02_grammer/sum.ts @@ -0,0 +1,5 @@ +function sum(a: number, b: number): number { + return a + b; +} + +sum(2, 3); // 5 From 8ccca6e86e5296a096ea5e1f8974e784f38276a0 Mon Sep 17 00:00:00 2001 From: Fendo181 Date: Thu, 29 May 2025 23:19:41 +0900 Subject: [PATCH 2/6] add: README.md --- study/typescript/README.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 study/typescript/README.md diff --git a/study/typescript/README.md b/study/typescript/README.md new file mode 100644 index 0000000..a12c988 --- /dev/null +++ b/study/typescript/README.md @@ -0,0 +1,8 @@ +### 手を動かしながら学ぶTypeScript + +手を動かしながら学ぶことは、プログラミングの習得において非常に重要です。以下は、TypeScriptを学ぶための具体的なステップです。 + +### 参考 + +- [TypeScript公式ドキュメント](https://www.typescriptlang.org/docs/) +- [手を動かしながら学ぶTypeScript](https://www.c-r.com/book/detail/1429) From 0fab59afa1e7fdcccc04d1b1b3a394f6d4dd7612 Mon Sep 17 00:00:00 2001 From: Fendo181 Date: Thu, 29 May 2025 23:23:09 +0900 Subject: [PATCH 3/6] cmd: tsc --init --- study/typescript/tsconfig.json | 113 +++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 study/typescript/tsconfig.json diff --git a/study/typescript/tsconfig.json b/study/typescript/tsconfig.json new file mode 100644 index 0000000..904d43f --- /dev/null +++ b/study/typescript/tsconfig.json @@ -0,0 +1,113 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "libReplacement": true, /* Enable lib replacement. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "noUncheckedSideEffectImports": true, /* Check side effect imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ + // "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} From deccfaf6fed3526fa0240f891941919a59eef726 Mon Sep 17 00:00:00 2001 From: Fendo181 Date: Thu, 29 May 2025 23:23:17 +0900 Subject: [PATCH 4/6] fix --- study/typescript/02_grammer/sum.js | 2 +- study/typescript/02_grammer/sum.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/study/typescript/02_grammer/sum.js b/study/typescript/02_grammer/sum.js index a6ca085..25afa76 100644 --- a/study/typescript/02_grammer/sum.js +++ b/study/typescript/02_grammer/sum.js @@ -1,4 +1,4 @@ function sum(a, b) { return a + b; } -console.log(sum(2, 3)); // 5 +sum(2, 4); // 5 diff --git a/study/typescript/02_grammer/sum.ts b/study/typescript/02_grammer/sum.ts index eab416a..57670b6 100644 --- a/study/typescript/02_grammer/sum.ts +++ b/study/typescript/02_grammer/sum.ts @@ -2,4 +2,4 @@ function sum(a: number, b: number): number { return a + b; } -sum(2, 3); // 5 +sum(2, 4); // 5 From 1c5164d4a51f6b7f0d9331f340032e99fcbf6224 Mon Sep 17 00:00:00 2001 From: Fendo181 Date: Fri, 30 May 2025 10:48:04 +0900 Subject: [PATCH 5/6] =?UTF-8?q?add:=20interface=E3=81=AE=E3=82=B5=E3=83=B3?= =?UTF-8?q?=E3=83=97=E3=83=AB=E3=82=B3=E3=83=BC=E3=83=89=E3=82=92=E8=BF=BD?= =?UTF-8?q?=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- study/typescript/02_grammer/interface.js | 5 +++++ study/typescript/02_grammer/interface.ts | 11 +++++++++++ 2 files changed, 16 insertions(+) create mode 100644 study/typescript/02_grammer/interface.js create mode 100644 study/typescript/02_grammer/interface.ts diff --git a/study/typescript/02_grammer/interface.js b/study/typescript/02_grammer/interface.js new file mode 100644 index 0000000..c4d1a7b --- /dev/null +++ b/study/typescript/02_grammer/interface.js @@ -0,0 +1,5 @@ +var dog = { + name: 'Don', + age: 3 +}; +console.log(dog.name); // Don diff --git a/study/typescript/02_grammer/interface.ts b/study/typescript/02_grammer/interface.ts new file mode 100644 index 0000000..a860b89 --- /dev/null +++ b/study/typescript/02_grammer/interface.ts @@ -0,0 +1,11 @@ +interface Animal { + name: string, + age: number +} + +const dog: Animal = { + name: 'Don', + age: 3 +}; + +console.log(dog.name) // Don From e57de116c12ee28c68395143344bf708c3423e51 Mon Sep 17 00:00:00 2001 From: Fendo181 Date: Fri, 30 May 2025 10:48:12 +0900 Subject: [PATCH 6/6] update: README.md --- study/typescript/README.md | 211 ++++++++++++++++++++++++++++++++++++- 1 file changed, 210 insertions(+), 1 deletion(-) diff --git a/study/typescript/README.md b/study/typescript/README.md index a12c988..06060fe 100644 --- a/study/typescript/README.md +++ b/study/typescript/README.md @@ -1,7 +1,216 @@ -### 手を動かしながら学ぶTypeScript +## 手を動かしながら学ぶTypeScript 手を動かしながら学ぶことは、プログラミングの習得において非常に重要です。以下は、TypeScriptを学ぶための具体的なステップです。 +### サンプルコード + +```typescript +function greet(name: string): string { + return `Hello, ${name}!`; +} +const userName: string = "Alice"; +console.log(greet(userName)); +``` + +tscコマンドを使用してTypeScriptファイルをコンパイルし、JavaScriptに変換します。 + +```bash +tsc greet.ts +``` + + `--target` オプションを使用して、出力するJavaScriptのバージョンを指定できます。 + +```bash +tsc greet.ts --target ES6 +``` + +### TypeScriptでの基本的な型 + +TypeScriptでは、以下の基本的な型が用意されています。 + +- `number`: 数値型 +- `string`: 文字列型 +- `boolean`: 真偽値型 +- `any`: 任意の型 +- `void`: 戻り値がない関数の型 +- `null`: null値 +- `undefined`: 未定義の値 +etc... + +型をあてる方法 + +```typescript +let num: number = 42; +let str: string = "Hello, TypeScript!"; +``` + +基本的には `let` や `const` を使用して変数を宣言し、その次に変数名を書き、コロン `:` の後に型を指定します。 +この `:number` の部分が型アノテーションと呼ばれます。 + + +#### nullとundefined +TypeScriptでは、`null` と `undefined` は特別な型として扱われます。 + +```typescript +let nullableValue: null = null; +let undefinedValue: undefined = undefined; +``` + +このように、`null` と `undefined` を明示的に型として指定することができます。 +大きな違いとしては + +- `null` は「値が存在しない」ことを示すために使用されます。 + - 意図して値が存在しないことを示すために使用されます。 +- `undefined` は「値が未定義」であることを示すために使用されます。 + - 意図して値が設定されていないことを示すために使用されます。 + +またこれら基本的に型と組み合わせる事でunion型を作成することができます。 + +```typescript +let value: string | null = null; // string型またはnull型 +let anotherValue: number | undefined = undefined; // number型またはundefined型 +``` + +#### strictNullChecksについて + +TypeScriptのコンパイラオプションの一つに `strictNullChecks` があります。 +このオプションを有効にすると、`null` と `undefined` が型システムにおいてより厳密に扱われます。 +これにより、`null` や `undefined` が許可されていない型に対しては、明示的に型アノテーションを指定する必要があります。 + +例えば strictNullChecksが有効な場合、以下のようなコードはエラーになります。 + +```typescript +let value: string = null; // エラー: 'null' は 'string' 型に割り当てられません +``` +一方、strictNullChecksが無効な場合は、`null` や `undefined` が暗黙的に許可されます。 + +```typescript +let value: string = null; // 問題なし +``` + +つまりは、`tsconfig.json` ファイルで `strictNullChecks` をfalseにしてしまうと、`null` や `undefined` が許可されてしまい、型安全性が低下します。 + +#### 関数型 + +TypeScriptでは、関数の型も定義できます。関数の引数や戻り値の型を指定することで、より安全なコードを書くことができます。 + +```typescript +// 関数の型としては nameをstring型で受取う、戻り値をstring型とする +const sayHello: (name: string) => string = (name: string) => { + return `Hello, ${name}!`; +}; + +/* これを省略なしでかくと +```typescript +const sayHello = (name: string): string => { + return `Hello, ${name}!`; +}; +*/ + +console.log(sayHello("TypeScript")); // Hello, TypeScript! +```  + +### オブジェクト型 + +TypeScriptでは、オブジェクトの型も定義できます。オブジェクトのプロパティやメソッドの型を指定することで、より明確なコードを書くことができます。 + +```typescript +// オブジェクトの型を定義 +interface User { + name: string; + age: number; + greet(): string; +} +// オブジェクトを作成 +const user: User = { + name: "Alice", + age: 30, + greet() { + return `Hello, my name is ${this.name} and I am ${this.age} years old.`; + } +}; +console.log(user.greet()); // Hello, my name is Alice and I am 30 years old. +``` + +オブジェクト型では`オプショナルプロパティ`も定義できます。オプショナルプロパティは、オブジェクトに存在しない可能性があるプロパティです。 + +```typescript + +interface User { + name: string; + age?: number; // オプショナルプロパティ +} +const user: User = { + name: "Bob" + // ageは省略可能 +}; +``` + +#### readonlyプロパティ + +TypeScriptでは、オブジェクトのプロパティを`readonly`として定義することができます。これにより、そのプロパティは読み取り専用となり、変更できなくなります。 + +```typescript +interface User { + readonly id: number; // 読み取り専用プロパティ + name: string; +} +const user: User = { + id: 1, + name: "Charlie" +}; +// user.id = 2; // エラー: 'id' は読み取り専用プロパティです +console.log(user.id); // 1 +``` + +#### any型 + +`any`型は、TypeScriptで最も柔軟な型であり、どんな値でも受け入れることができます。ただし、`any`型を多用すると、型安全性が失われるため、注意が必要です。 + +```typescript +let value: any = "Hello, TypeScript!"; +value = 42; // 数値も許可される +value = { message: "This is an object" }; // オブジェクトも許可される +console.log(value); +``` + +any型は、特に外部ライブラリやAPIとの連携時に便利ですが、可能な限り具体的な型を使用することが推奨されます。 +なぜなら、`any`型を使用すると、TypeScriptの型チェックの利点が失われ、ランタイムエラーのリスクが高まるからです。 + +#### interface + +`interface`は、TypeScriptでオブジェクトの構造を定義するための方法です。`interface`を使用すると、オブジェクトのプロパティやメソッドの型を明確に指定できます。 + +```typescript +interface Animal { + name: string, + age: number +} + +const dog: Animal = { + name: 'Don', + age: 3 +}; + +console.log(dog.name) // Don + +``` +### 型推論という概念の紹介 + +TypeScriptは、変数や関数の型を自動的に推論する機能を持っています。これにより、明示的に型を指定しなくても、TypeScriptが適切な型を推測してくれます。 + +```typescript +let message = "Hello, TypeScript!"; +let count = 42; +function greet(name: string) { + return `Hello, ${name}!`; +} +``` + +この例では、`message`は自動的に`string`型として推論され、`count`は`number`型として推論されます。また、`greet`関数の引数`name`も`string`型として推論されます。 +これは + + ### 参考 - [TypeScript公式ドキュメント](https://www.typescriptlang.org/docs/)