根据官方内容同步本地文档 #2
+14
-4
@@ -1,5 +1,11 @@
|
||||
import fs from 'node:fs';
|
||||
import { defineConfig, type DefaultTheme } from 'vitepress';
|
||||
|
||||
// Sidebar of the official documentation, written by scripts/import-typescript-website.mjs.
|
||||
const docsSidebar: DefaultTheme.SidebarItem[] = JSON.parse(
|
||||
fs.readFileSync(new URL('../scripts/nav.json', import.meta.url), 'utf8'));
|
||||
|
||||
const UPSTREAM_REPO_URL = 'https://github.com/microsoft/TypeScript-website';
|
||||
const FORUM_URL = 'https://www.isharkfly.com/';
|
||||
const REPO_URL = 'https://src.sharkdat.com/iSharkFly-Docs/TypeScript-iSharkFly-Com';
|
||||
|
||||
@@ -15,7 +21,7 @@ function isharkflyNav(): DefaultTheme.NavItem {
|
||||
};
|
||||
}
|
||||
|
||||
const sidebar: DefaultTheme.Sidebar = [
|
||||
const guideSidebar: DefaultTheme.SidebarItem[] = [
|
||||
{
|
||||
text: 'TypeScript 文档手册',
|
||||
items: [
|
||||
@@ -91,11 +97,15 @@ export default defineConfig({
|
||||
themeConfig: {
|
||||
logo: 'https://www.typescriptlang.org/favicon-32x32.png',
|
||||
nav: [
|
||||
{ text: '文档', link: '/overview/', activeMatch: '^/overview/' },
|
||||
{ text: '官方文档', link: '/docs/handbook/intro', activeMatch: '^/docs/' },
|
||||
{ text: '简介', link: '/overview/', activeMatch: '^/overview/' },
|
||||
{ text: '关于', link: '/about', activeMatch: '^/(about|contact)' },
|
||||
isharkflyNav(),
|
||||
],
|
||||
sidebar,
|
||||
sidebar: {
|
||||
'/docs/': docsSidebar,
|
||||
'/': guideSidebar,
|
||||
},
|
||||
search: {
|
||||
provider: 'local',
|
||||
options: { translations: zhSearchText },
|
||||
@@ -115,7 +125,7 @@ export default defineConfig({
|
||||
linkText: '返回首页',
|
||||
},
|
||||
socialLinks: [
|
||||
{ icon: 'github', link: 'https://github.com/microsoft/TypeScript' },
|
||||
{ icon: 'github', link: UPSTREAM_REPO_URL },
|
||||
],
|
||||
footer: {
|
||||
message: '本书采用「保持署名—非商用」创意共享 4.0 许可证。',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 cwiki-us-docs
|
||||
Copyright (c) 2026 iSharkFly.Com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -20,6 +20,18 @@
|
||||
- 向作者 [提交 issue](https://github.com/cwiki-us-docs/typescript-docs-cn)
|
||||
- 欢迎直接提交 pull-request 参与贡献
|
||||
|
||||
## 官方文档
|
||||
|
||||
站点中的「官方文档」(`site/docs/`)导入自 TypeScript 官方文档仓库 [microsoft/TypeScript-website](https://github.com/microsoft/TypeScript-website)
|
||||
(`packages/documentation/copy/en`),保持英文原文,未进行翻译。导入的版本记录在 `scripts/upstream.json` 中。
|
||||
|
||||
更新官方文档:
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/microsoft/TypeScript-website.git ../TypeScript-website
|
||||
node scripts/import-typescript-website.mjs ../TypeScript-website
|
||||
```
|
||||
|
||||
## 关于 TypeScript
|
||||
|
||||
[TypeScript] 是 JavaScript 的一个超集,主要提供了**类型系统**和**对 ES6 的支持**,它由 Microsoft 开发,代码[开源于 GitHub](https://github.com/Microsoft/TypeScript) 上。
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"repository": "https://github.com/microsoft/TypeScript-website",
|
||||
"commit": "bfee36f956e2f15cc48b5a10516dfd857a1607ba",
|
||||
"source": "packages/documentation/copy/en"
|
||||
}
|
||||
@@ -20,6 +20,18 @@
|
||||
- 向作者 [提交 issue](https://github.com/cwiki-us-docs/typescript-docs-cn)
|
||||
- 欢迎直接提交 pull-request 参与贡献
|
||||
|
||||
## 官方文档
|
||||
|
||||
站点中的「官方文档」(`site/docs/`)导入自 TypeScript 官方文档仓库 [microsoft/TypeScript-website](https://github.com/microsoft/TypeScript-website)
|
||||
(`packages/documentation/copy/en`),保持英文原文,未进行翻译。导入的版本记录在 `scripts/upstream.json` 中。
|
||||
|
||||
更新官方文档:
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/microsoft/TypeScript-website.git ../TypeScript-website
|
||||
node scripts/import-typescript-website.mjs ../TypeScript-website
|
||||
```
|
||||
|
||||
## 关于 TypeScript
|
||||
|
||||
[TypeScript] 是 JavaScript 的一个超集,主要提供了**类型系统**和**对 ES6 的支持**,它由 Microsoft 开发,代码[开源于 GitHub](https://github.com/Microsoft/TypeScript) 上。
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,225 @@
|
||||
---
|
||||
title: "Conditional Types"
|
||||
description: "Create types which act like if statements in the type system."
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Conditional Types.md"
|
||||
---
|
||||
|
||||
# Conditional Types
|
||||
|
||||
At the heart of most useful programs, we have to make decisions based on input.
|
||||
JavaScript programs are no different, but given the fact that values can be easily introspected, those decisions are also based on the types of the inputs.
|
||||
_Conditional types_ help describe the relation between the types of inputs and outputs.
|
||||
|
||||
```ts
|
||||
interface Animal {
|
||||
live(): void;
|
||||
}
|
||||
interface Dog extends Animal {
|
||||
woof(): void;
|
||||
}
|
||||
|
||||
type Example1 = Dog extends Animal ? number : string;
|
||||
|
||||
type Example2 = RegExp extends Animal ? number : string;
|
||||
```
|
||||
|
||||
Conditional types take a form that looks a little like conditional expressions (`condition ? trueExpression : falseExpression`) in JavaScript:
|
||||
|
||||
```ts
|
||||
SomeType extends OtherType ? TrueType : FalseType;
|
||||
```
|
||||
|
||||
When the type on the left of the `extends` is assignable to the one on the right, then you'll get the type in the first branch (the "true" branch); otherwise you'll get the type in the latter branch (the "false" branch).
|
||||
|
||||
From the examples above, conditional types might not immediately seem useful - we can tell ourselves whether or not `Dog extends Animal` and pick `number` or `string`!
|
||||
But the power of conditional types comes from using them with generics.
|
||||
|
||||
For example, let's take the following `createLabel` function:
|
||||
|
||||
```ts
|
||||
interface IdLabel {
|
||||
id: number /* some fields */;
|
||||
}
|
||||
interface NameLabel {
|
||||
name: string /* other fields */;
|
||||
}
|
||||
|
||||
function createLabel(id: number): IdLabel;
|
||||
function createLabel(name: string): NameLabel;
|
||||
function createLabel(nameOrId: string | number): IdLabel | NameLabel;
|
||||
function createLabel(nameOrId: string | number): IdLabel | NameLabel {
|
||||
throw "unimplemented";
|
||||
}
|
||||
```
|
||||
|
||||
These overloads for createLabel describe a single JavaScript function that makes a choice based on the types of its inputs. Note a few things:
|
||||
|
||||
1. If a library has to make the same sort of choice over and over throughout its API, this becomes cumbersome.
|
||||
2. We have to create three overloads: one for each case when we're _sure_ of the type (one for `string` and one for `number`), and one for the most general case (taking a `string | number`). For every new type `createLabel` can handle, the number of overloads grows exponentially.
|
||||
|
||||
Instead, we can encode that logic in a conditional type:
|
||||
|
||||
```ts
|
||||
type NameOrId<T extends number | string> = T extends number
|
||||
? IdLabel
|
||||
: NameLabel;
|
||||
```
|
||||
|
||||
We can then use that conditional type to simplify our overloads down to a single function with no overloads.
|
||||
|
||||
```ts
|
||||
function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
|
||||
throw "unimplemented";
|
||||
}
|
||||
|
||||
let a = createLabel("typescript");
|
||||
|
||||
let b = createLabel(2.8);
|
||||
|
||||
let c = createLabel(Math.random() ? "hello" : 42);
|
||||
```
|
||||
|
||||
## Conditional Type Constraints
|
||||
|
||||
Often, the checks in a conditional type will provide us with some new information.
|
||||
Just like narrowing with type guards can give us a more specific type, the true branch of a conditional type will further constrain generics by the type we check against.
|
||||
|
||||
For example, let's take the following:
|
||||
|
||||
```ts
|
||||
type MessageOf<T> = T["message"];
|
||||
```
|
||||
|
||||
In this example, TypeScript errors because `T` isn't known to have a property called `message`.
|
||||
We could constrain `T`, and TypeScript would no longer complain:
|
||||
|
||||
```ts
|
||||
type MessageOf<T extends { message: unknown }> = T["message"];
|
||||
|
||||
interface Email {
|
||||
message: string;
|
||||
}
|
||||
|
||||
type EmailMessageContents = MessageOf<Email>;
|
||||
```
|
||||
|
||||
However, what if we wanted `MessageOf` to take any type, and default to something like `never` if a `message` property isn't available?
|
||||
We can do this by moving the constraint out and introducing a conditional type:
|
||||
|
||||
```ts
|
||||
type MessageOf<T> = T extends { message: unknown } ? T["message"] : never;
|
||||
|
||||
interface Email {
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface Dog {
|
||||
bark(): void;
|
||||
}
|
||||
|
||||
type EmailMessageContents = MessageOf<Email>;
|
||||
|
||||
type DogMessageContents = MessageOf<Dog>;
|
||||
```
|
||||
|
||||
Within the true branch, TypeScript knows that `T` _will_ have a `message` property.
|
||||
|
||||
As another example, we could also write a type called `Flatten` that flattens array types to their element types, but leaves them alone otherwise:
|
||||
|
||||
```ts
|
||||
type Flatten<T> = T extends any[] ? T[number] : T;
|
||||
|
||||
// Extracts out the element type.
|
||||
type Str = Flatten<string[]>;
|
||||
|
||||
// Leaves the type alone.
|
||||
type Num = Flatten<number>;
|
||||
```
|
||||
|
||||
When `Flatten` is given an array type, it uses an indexed access with `number` to fetch out `string[]`'s element type.
|
||||
Otherwise, it just returns the type it was given.
|
||||
|
||||
## Inferring Within Conditional Types
|
||||
|
||||
We just found ourselves using conditional types to apply constraints and then extract out types.
|
||||
This ends up being such a common operation that conditional types make it easier.
|
||||
|
||||
Conditional types provide us with a way to infer from types we compare against in the true branch using the `infer` keyword.
|
||||
For example, we could have inferred the element type in `Flatten` instead of fetching it out "manually" with an indexed access type:
|
||||
|
||||
```ts
|
||||
type Flatten<Type> = Type extends Array<infer Item> ? Item : Type;
|
||||
```
|
||||
|
||||
Here, we used the `infer` keyword to declaratively introduce a new generic type variable named `Item` instead of specifying how to retrieve the element type of `Type` within the true branch.
|
||||
This frees us from having to think about how to dig through and probing apart the structure of the types we're interested in.
|
||||
|
||||
We can write some useful helper type aliases using the `infer` keyword.
|
||||
For example, for simple cases, we can extract the return type out from function types:
|
||||
|
||||
```ts
|
||||
type GetReturnType<Type> = Type extends (...args: never[]) => infer Return
|
||||
? Return
|
||||
: never;
|
||||
|
||||
type Num = GetReturnType<() => number>;
|
||||
|
||||
type Str = GetReturnType<(x: string) => string>;
|
||||
|
||||
type Bools = GetReturnType<(a: boolean, b: boolean) => boolean[]>;
|
||||
```
|
||||
|
||||
When inferring from a type with multiple call signatures (such as the type of an overloaded function), inferences are made from the _last_ signature (which, presumably, is the most permissive catch-all case). It is not possible to perform overload resolution based on a list of argument types.
|
||||
|
||||
```ts
|
||||
declare function stringOrNum(x: string): number;
|
||||
declare function stringOrNum(x: number): string;
|
||||
declare function stringOrNum(x: string | number): string | number;
|
||||
|
||||
type T1 = ReturnType<typeof stringOrNum>;
|
||||
```
|
||||
|
||||
## Distributive Conditional Types
|
||||
|
||||
When conditional types act on a generic type, they become _distributive_ when given a union type.
|
||||
For example, take the following:
|
||||
|
||||
```ts
|
||||
type ToArray<Type> = Type extends any ? Type[] : never;
|
||||
```
|
||||
|
||||
If we plug a union type into `ToArray`, then the conditional type will be applied to each member of that union.
|
||||
|
||||
```ts
|
||||
type ToArray<Type> = Type extends any ? Type[] : never;
|
||||
|
||||
type StrArrOrNumArr = ToArray<string | number>;
|
||||
```
|
||||
|
||||
What happens here is that `ToArray` distributes on:
|
||||
|
||||
```ts
|
||||
string | number;
|
||||
```
|
||||
|
||||
and maps over each member type of the union, to what is effectively:
|
||||
|
||||
```ts
|
||||
ToArray<string> | ToArray<number>;
|
||||
```
|
||||
|
||||
which leaves us with:
|
||||
|
||||
```ts
|
||||
string[] | number[];
|
||||
```
|
||||
|
||||
Typically, distributivity is the desired behavior.
|
||||
To avoid that behavior, you can surround each side of the `extends` keyword with square brackets.
|
||||
|
||||
```ts
|
||||
type ToArrayNonDist<Type> = [Type] extends [any] ? Type[] : never;
|
||||
|
||||
// 'ArrOfStrOrNum' is no longer a union.
|
||||
type ArrOfStrOrNum = ToArrayNonDist<string | number>;
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,61 @@
|
||||
---
|
||||
title: "Indexed Access Types"
|
||||
description: "Using Type['a'] syntax to access a subset of a type."
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Indexed Access Types.md"
|
||||
---
|
||||
|
||||
# Indexed Access Types
|
||||
|
||||
We can use an _indexed access type_ to look up a specific property on another type:
|
||||
|
||||
```ts
|
||||
type Person = { age: number; name: string; alive: boolean };
|
||||
type Age = Person["age"];
|
||||
```
|
||||
|
||||
The indexing type is itself a type, so we can use unions, `keyof`, or other types entirely:
|
||||
|
||||
```ts
|
||||
type I1 = Person["age" | "name"];
|
||||
|
||||
type I2 = Person[keyof Person];
|
||||
|
||||
type AliveOrName = "alive" | "name";
|
||||
type I3 = Person[AliveOrName];
|
||||
```
|
||||
|
||||
You'll even see an error if you try to index a property that doesn't exist:
|
||||
|
||||
```ts
|
||||
type I1 = Person["alve"];
|
||||
```
|
||||
|
||||
Another example of indexing with an arbitrary type is using `number` to get the type of an array's elements.
|
||||
We can combine this with `typeof` to conveniently capture the element type of an array literal:
|
||||
|
||||
```ts
|
||||
const MyArray = [
|
||||
{ name: "Alice", age: 15 },
|
||||
{ name: "Bob", age: 23 },
|
||||
{ name: "Eve", age: 38 },
|
||||
];
|
||||
|
||||
type Person = typeof MyArray[number];
|
||||
type Age = typeof MyArray[number]["age"];
|
||||
// Or
|
||||
type Age2 = Person["age"];
|
||||
```
|
||||
|
||||
You can only use types when indexing, meaning you can't use a `const` to make a variable reference:
|
||||
|
||||
```ts
|
||||
const key = "age";
|
||||
type Age = Person[key];
|
||||
```
|
||||
|
||||
However, you can use a type alias for a similar style of refactor:
|
||||
|
||||
```ts
|
||||
type key = "age";
|
||||
type Age = Person[key];
|
||||
```
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
title: "Keyof Type Operator"
|
||||
description: "Using the keyof operator in type contexts."
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Keyof Type Operator.md"
|
||||
---
|
||||
|
||||
# Keyof Type Operator
|
||||
|
||||
## The `keyof` type operator
|
||||
|
||||
The `keyof` operator takes an object type and produces a string or numeric literal union of its keys.
|
||||
The following type `P` is the same type as `type P = "x" | "y"`:
|
||||
|
||||
```ts
|
||||
type Point = { x: number; y: number };
|
||||
type P = keyof Point;
|
||||
```
|
||||
|
||||
If the type has a `string` or `number` index signature, `keyof` will return those types instead:
|
||||
|
||||
```ts
|
||||
type Arrayish = { [n: number]: unknown };
|
||||
type A = keyof Arrayish;
|
||||
|
||||
type Mapish = { [k: string]: boolean };
|
||||
type M = keyof Mapish;
|
||||
```
|
||||
|
||||
Note that in this example, `M` is `string | number` -- this is because JavaScript object keys are always coerced to a string, so `obj[0]` is always the same as `obj["0"]`.
|
||||
|
||||
`keyof` types become especially useful when combined with mapped types, which we'll learn more about later.
|
||||
@@ -0,0 +1,148 @@
|
||||
---
|
||||
title: "Mapped Types"
|
||||
description: "Generating types by re-using an existing type."
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Mapped Types.md"
|
||||
---
|
||||
|
||||
# Mapped Types
|
||||
|
||||
When you don't want to repeat yourself, sometimes a type needs to be based on another type.
|
||||
|
||||
Mapped types build on the syntax for index signatures, which are used to declare the types of properties which have not been declared ahead of time:
|
||||
|
||||
```ts
|
||||
type OnlyBoolsAndHorses = {
|
||||
[key: string]: boolean | Horse;
|
||||
};
|
||||
|
||||
const conforms: OnlyBoolsAndHorses = {
|
||||
del: true,
|
||||
rodney: false,
|
||||
};
|
||||
```
|
||||
|
||||
A mapped type is a generic type which uses a union of `PropertyKey`s (frequently created [via a `keyof`](/docs/handbook/2/indexed-access-types)) to iterate through keys to create a type:
|
||||
|
||||
```ts
|
||||
type OptionsFlags<Type> = {
|
||||
[Property in keyof Type]: boolean;
|
||||
};
|
||||
```
|
||||
|
||||
In this example, `OptionsFlags` will take all the properties from the type `Type` and change their values to be a boolean.
|
||||
|
||||
```ts
|
||||
type Features = {
|
||||
darkMode: () => void;
|
||||
newUserProfile: () => void;
|
||||
};
|
||||
|
||||
type FeatureOptions = OptionsFlags<Features>;
|
||||
```
|
||||
|
||||
## Mapping Modifiers
|
||||
|
||||
There are two additional modifiers which can be applied during mapping: `readonly` and `?` which affect mutability and optionality respectively.
|
||||
|
||||
You can remove or add these modifiers by prefixing with `-` or `+`. If you don't add a prefix, then `+` is assumed.
|
||||
|
||||
```ts
|
||||
// Removes 'readonly' attributes from a type's properties
|
||||
type CreateMutable<Type> = {
|
||||
-readonly [Property in keyof Type]: Type[Property];
|
||||
};
|
||||
|
||||
type LockedAccount = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
};
|
||||
|
||||
type UnlockedAccount = CreateMutable<LockedAccount>;
|
||||
```
|
||||
|
||||
```ts
|
||||
// Removes 'optional' attributes from a type's properties
|
||||
type Concrete<Type> = {
|
||||
[Property in keyof Type]-?: Type[Property];
|
||||
};
|
||||
|
||||
type MaybeUser = {
|
||||
id: string;
|
||||
name?: string;
|
||||
age?: number;
|
||||
};
|
||||
|
||||
type User = Concrete<MaybeUser>;
|
||||
```
|
||||
|
||||
## Key Remapping via `as`
|
||||
|
||||
In TypeScript 4.1 and onwards, you can re-map keys in mapped types with an `as` clause in a mapped type:
|
||||
|
||||
```ts
|
||||
type MappedTypeWithNewProperties<Type> = {
|
||||
[Properties in keyof Type as NewKeyType]: Type[Properties]
|
||||
}
|
||||
```
|
||||
|
||||
You can leverage features like [template literal types](/docs/handbook/2/template-literal-types) to create new property names from prior ones:
|
||||
|
||||
```ts
|
||||
type Getters<Type> = {
|
||||
[Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property]
|
||||
};
|
||||
|
||||
interface Person {
|
||||
name: string;
|
||||
age: number;
|
||||
location: string;
|
||||
}
|
||||
|
||||
type LazyPerson = Getters<Person>;
|
||||
```
|
||||
|
||||
You can filter out keys by producing `never` via a conditional type:
|
||||
|
||||
```ts
|
||||
// Remove the 'kind' property
|
||||
type RemoveKindField<Type> = {
|
||||
[Property in keyof Type as Exclude<Property, "kind">]: Type[Property]
|
||||
};
|
||||
|
||||
interface Circle {
|
||||
kind: "circle";
|
||||
radius: number;
|
||||
}
|
||||
|
||||
type KindlessCircle = RemoveKindField<Circle>;
|
||||
```
|
||||
|
||||
You can map over arbitrary unions, not just unions of `string | number | symbol`, but unions of any type:
|
||||
|
||||
```ts
|
||||
type EventConfig<Events extends { kind: string }> = {
|
||||
[E in Events as E["kind"]]: (event: E) => void;
|
||||
}
|
||||
|
||||
type SquareEvent = { kind: "square", x: number, y: number };
|
||||
type CircleEvent = { kind: "circle", radius: number };
|
||||
|
||||
type Config = EventConfig<SquareEvent | CircleEvent>
|
||||
```
|
||||
|
||||
### Further Exploration
|
||||
|
||||
Mapped types work well with other features in this type manipulation section, for example here is [a mapped type using a conditional type](/docs/handbook/2/conditional-types) which returns either a `true` or `false` depending on whether an object has the property `pii` set to the literal `true`:
|
||||
|
||||
```ts
|
||||
type ExtractPII<Type> = {
|
||||
[Property in keyof Type]: Type[Property] extends { pii: true } ? true : false;
|
||||
};
|
||||
|
||||
type DBFields = {
|
||||
id: { format: "incrementing" };
|
||||
name: { type: string; pii: true };
|
||||
};
|
||||
|
||||
type ObjectsNeedingGDPRDeletion = ExtractPII<DBFields>;
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,225 @@
|
||||
---
|
||||
title: "Template Literal Types"
|
||||
description: "Generating mapping types which change properties via template literal strings."
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Template Literal Types.md"
|
||||
---
|
||||
|
||||
# Template Literal Types
|
||||
|
||||
Template literal types build on [string literal types](/docs/handbook/2/everyday-types#literal-types), and have the ability to expand into many strings via unions.
|
||||
|
||||
They have the same syntax as [template literal strings in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), but are used in type positions.
|
||||
When used with concrete literal types, a template literal produces a new string literal type by concatenating the contents.
|
||||
|
||||
```ts
|
||||
type World = "world";
|
||||
|
||||
type Greeting = `hello ${World}`;
|
||||
```
|
||||
|
||||
When a union is used in the interpolated position, the type is the set of every possible string literal that could be represented by each union member:
|
||||
|
||||
```ts
|
||||
type EmailLocaleIDs = "welcome_email" | "email_heading";
|
||||
type FooterLocaleIDs = "footer_title" | "footer_sendoff";
|
||||
|
||||
type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;
|
||||
```
|
||||
|
||||
For each interpolated position in the template literal, the unions are cross multiplied:
|
||||
|
||||
```ts
|
||||
type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;
|
||||
type Lang = "en" | "ja" | "pt";
|
||||
|
||||
type LocaleMessageIDs = `${Lang}_${AllLocaleIDs}`;
|
||||
```
|
||||
|
||||
We generally recommend that people use ahead-of-time generation for large string unions, but this is useful in smaller cases.
|
||||
|
||||
## String Unions in Types
|
||||
|
||||
The power in template literals comes when defining a new string based on information inside a type.
|
||||
|
||||
Consider the case where a function (`makeWatchedObject`) adds a new function
|
||||
called `on()` to a passed object. In JavaScript, its call might look like:
|
||||
`makeWatchedObject(baseObject)`. We can imagine the base object as looking
|
||||
like:
|
||||
|
||||
```ts
|
||||
const passedObject = {
|
||||
firstName: "Saoirse",
|
||||
lastName: "Ronan",
|
||||
age: 26,
|
||||
};
|
||||
```
|
||||
|
||||
The `on` function that will be added to the base object expects two arguments, an `eventName` (a `string`) and a `callback` (a `function`).
|
||||
|
||||
The `eventName` should be of the form `attributeInThePassedObject + "Changed"`; thus, `firstNameChanged` as derived from the attribute `firstName` in the base object.
|
||||
|
||||
The `callback` function, when called:
|
||||
* Should be passed a value of the type associated with the name `attributeInThePassedObject`; thus, since `firstName` is typed as `string`, the callback for the `firstNameChanged` event expects a `string` to be passed to it at call time. Similarly events associated with `age` should expect to be called with a `number` argument
|
||||
* Should have `void` return type (for simplicity of demonstration)
|
||||
|
||||
The naive function signature of `on()` might thus be: `on(eventName: string, callback: (newValue: any) => void)`. However, in the preceding description, we identified important type constraints that we'd like to document in our code. Template Literal types let us bring these constraints into our code.
|
||||
|
||||
```ts
|
||||
const person = makeWatchedObject({
|
||||
firstName: "Saoirse",
|
||||
lastName: "Ronan",
|
||||
age: 26,
|
||||
});
|
||||
|
||||
// makeWatchedObject has added `on` to the anonymous Object
|
||||
|
||||
person.on("firstNameChanged", (newValue) => {
|
||||
console.log(`firstName was changed to ${newValue}!`);
|
||||
});
|
||||
```
|
||||
|
||||
Notice that `on` listens on the event `"firstNameChanged"`, not just `"firstName"`. Our naive specification of `on()` could be made more robust if we were to ensure that the set of eligible event names was constrained by the union of attribute names in the watched object with "Changed" added at the end. While we are comfortable with doing such a calculation in JavaScript i.e. ``Object.keys(passedObject).map(x => `${x}Changed`)``, template literals _inside the type system_ provide a similar approach to string manipulation:
|
||||
|
||||
```ts
|
||||
type PropEventSource<Type> = {
|
||||
on(eventName: `${string & keyof Type}Changed`, callback: (newValue: any) => void): void;
|
||||
};
|
||||
|
||||
/// Create a "watched object" with an `on` method
|
||||
/// so that you can watch for changes to properties.
|
||||
declare function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type>;
|
||||
```
|
||||
|
||||
With this, we can build something that errors when given the wrong property:
|
||||
|
||||
```ts
|
||||
const person = makeWatchedObject({
|
||||
firstName: "Saoirse",
|
||||
lastName: "Ronan",
|
||||
age: 26
|
||||
});
|
||||
|
||||
person.on("firstNameChanged", () => {});
|
||||
|
||||
// Prevent easy human error (using the key instead of the event name)
|
||||
person.on("firstName", () => {});
|
||||
|
||||
// It's typo-resistant
|
||||
person.on("frstNameChanged", () => {});
|
||||
```
|
||||
|
||||
## Inference with Template Literals
|
||||
|
||||
Notice that we did not benefit from all the information provided in the original passed object. Given change of a `firstName` (i.e. a `firstNameChanged` event), we should expect that the callback will receive an argument of type `string`. Similarly, the callback for a change to `age` should receive a `number` argument. We're naively using `any` to type the `callback`'s argument. Again, template literal types make it possible to ensure an attribute's data type will be the same type as that attribute's callback's first argument.
|
||||
|
||||
The key insight that makes this possible is this: we can use a function with a generic such that:
|
||||
|
||||
1. The literal used in the first argument is captured as a literal type
|
||||
2. That literal type can be validated as being in the union of valid attributes in the generic
|
||||
3. The type of the validated attribute can be looked up in the generic's structure using Indexed Access
|
||||
4. This typing information can _then_ be applied to ensure the argument to the
|
||||
callback function is of the same type
|
||||
|
||||
|
||||
```ts
|
||||
type PropEventSource<Type> = {
|
||||
on<Key extends string & keyof Type>
|
||||
(eventName: `${Key}Changed`, callback: (newValue: Type[Key]) => void): void;
|
||||
};
|
||||
|
||||
declare function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type>;
|
||||
|
||||
const person = makeWatchedObject({
|
||||
firstName: "Saoirse",
|
||||
lastName: "Ronan",
|
||||
age: 26
|
||||
});
|
||||
|
||||
person.on("firstNameChanged", newName => {
|
||||
console.log(`new name is ${newName.toUpperCase()}`);
|
||||
});
|
||||
|
||||
person.on("ageChanged", newAge => {
|
||||
if (newAge < 0) {
|
||||
console.warn("warning! negative age");
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Here we made `on` into a generic method.
|
||||
|
||||
When a user calls with the string `"firstNameChanged"`, TypeScript will try to infer the right type for `Key`.
|
||||
To do that, it will match `Key` against the content before `"Changed"` and infer the string `"firstName"`.
|
||||
Once TypeScript figures that out, the `on` method can fetch the type of `firstName` on the original object, which is `string` in this case.
|
||||
Similarly, when called with `"ageChanged"`, TypeScript finds the type for the property `age` which is `number`.
|
||||
|
||||
Inference can be combined in different ways, often to deconstruct strings, and reconstruct them in different ways.
|
||||
|
||||
## Intrinsic String Manipulation Types
|
||||
|
||||
To help with string manipulation, TypeScript includes a set of types which can be used in string manipulation. These types come built-in to the compiler for performance and can't be found in the `.d.ts` files included with TypeScript.
|
||||
|
||||
### `Uppercase<StringType>`
|
||||
|
||||
Converts each character in the string to the uppercase version.
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
type Greeting = "Hello, world"
|
||||
type ShoutyGreeting = Uppercase<Greeting>
|
||||
|
||||
type ASCIICacheKey<Str extends string> = `ID-${Uppercase<Str>}`
|
||||
type MainID = ASCIICacheKey<"my_app">
|
||||
```
|
||||
|
||||
### `Lowercase<StringType>`
|
||||
|
||||
Converts each character in the string to the lowercase equivalent.
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
type Greeting = "Hello, world"
|
||||
type QuietGreeting = Lowercase<Greeting>
|
||||
|
||||
type ASCIICacheKey<Str extends string> = `id-${Lowercase<Str>}`
|
||||
type MainID = ASCIICacheKey<"MY_APP">
|
||||
```
|
||||
|
||||
### `Capitalize<StringType>`
|
||||
|
||||
Converts the first character in the string to an uppercase equivalent.
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
type LowercaseGreeting = "hello, world";
|
||||
type Greeting = Capitalize<LowercaseGreeting>;
|
||||
```
|
||||
|
||||
### `Uncapitalize<StringType>`
|
||||
|
||||
Converts the first character in the string to a lowercase equivalent.
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
type UppercaseGreeting = "HELLO WORLD";
|
||||
type UncomfortableGreeting = Uncapitalize<UppercaseGreeting>;
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Technical details on the intrinsic string manipulation types</summary>
|
||||
<p>The code, as of TypeScript 4.1, for these intrinsic functions uses the JavaScript string runtime functions directly for manipulation and are not locale aware.</p>
|
||||
<code><pre>
|
||||
function applyStringMapping(symbol: Symbol, str: string) {
|
||||
switch (intrinsicTypeKinds.get(symbol.escapedName as string)) {
|
||||
case IntrinsicTypeKind.Uppercase: return str.toUpperCase();
|
||||
case IntrinsicTypeKind.Lowercase: return str.toLowerCase();
|
||||
case IntrinsicTypeKind.Capitalize: return str.charAt(0).toUpperCase() + str.slice(1);
|
||||
case IntrinsicTypeKind.Uncapitalize: return str.charAt(0).toLowerCase() + str.slice(1);
|
||||
}
|
||||
return str;
|
||||
}</pre></code>
|
||||
</details>
|
||||
@@ -0,0 +1,100 @@
|
||||
---
|
||||
title: "Type Declarations"
|
||||
description: "How TypeScript provides types for un-typed JavaScript."
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Declarations.md"
|
||||
---
|
||||
|
||||
# Type Declarations
|
||||
|
||||
Throughout the sections you've read so far, we've been demonstrating basic TypeScript concepts using the built-in functions present in all JavaScript runtimes.
|
||||
However, almost all JavaScript today includes many libraries to accomplish common tasks.
|
||||
Having types for the parts of your application that _aren't_ your code will greatly improve your TypeScript experience.
|
||||
Where do these types come from?
|
||||
|
||||
## What Do Type Declarations Look Like?
|
||||
|
||||
Let's say you write some code like this:
|
||||
|
||||
```ts
|
||||
const k = Math.max(5, 6);
|
||||
const j = Math.mix(7, 8);
|
||||
```
|
||||
|
||||
How did TypeScript know that `max` was present but not `mix`, even though `Math`'s implementation wasn't part of your code?
|
||||
|
||||
The answer is that there are _declaration files_ describing these built-in objects.
|
||||
A declaration file provides a way to _declare_ the existence of some types or values without actually providing implementations for those values.
|
||||
|
||||
## `.d.ts` files
|
||||
|
||||
TypeScript has two main kinds of files.
|
||||
`.ts` files are _implementation_ files that contain types and executable code.
|
||||
These are the files that produce `.js` outputs, and are where you'd normally write your code.
|
||||
|
||||
`.d.ts` files are _declaration_ files that contain _only_ type information.
|
||||
These files don't produce `.js` outputs; they are only used for typechecking.
|
||||
We'll learn more about how to write our own declaration files later.
|
||||
|
||||
## Built-in Type Definitions
|
||||
|
||||
TypeScript includes declaration files for all of the standardized built-in APIs available in JavaScript runtimes.
|
||||
This includes things like methods and properties of built-in types like `string` or `function`, top-level names like `Math` and `Object`, and their associated types.
|
||||
By default, TypeScript also includes types for things available when running inside the browser, such as `window` and `document`; these are collectively referred to as the DOM APIs.
|
||||
|
||||
TypeScript names these declaration files with the pattern `lib.[something].d.ts`.
|
||||
If you navigate into a file with that name, you can know that you're dealing with some built-in part of the platform, not user code.
|
||||
|
||||
### `target` setting
|
||||
|
||||
The methods, properties, and functions available to you actually vary based on the _version_ of JavaScript your code is running on.
|
||||
For example, the `startsWith` method of strings is available only starting with the version of JavaScript referred as _ECMAScript 6_.
|
||||
|
||||
Being aware of what version of JavaScript your code ultimately runs on is important because you don't want to use APIs that are from a newer version than the platform you deploy to.
|
||||
This is one function of the [`target`](https://www.typescriptlang.org/tsconfig#target) compiler setting.
|
||||
|
||||
TypeScript helps with this problem by varying which `lib` files are included by default based on your [`target`](https://www.typescriptlang.org/tsconfig#target) setting.
|
||||
For example, if [`target`](https://www.typescriptlang.org/tsconfig#target) is `ES5`, you will see an error if trying to use the `startsWith` method, because that method is only available in `ES6` or later.
|
||||
|
||||
### `lib` setting
|
||||
|
||||
The [`lib`](https://www.typescriptlang.org/tsconfig#lib) setting allows more fine-grained control of which built-in declaration files are considered available in your program.
|
||||
See the documentation page on [`lib`](https://www.typescriptlang.org/tsconfig#lib) for more information.
|
||||
|
||||
## External Definitions
|
||||
|
||||
For non-built-in APIs, there are a variety of ways you can get declaration files.
|
||||
How you do this depends on exactly which library you're getting types for.
|
||||
|
||||
### Bundled Types
|
||||
|
||||
If a library you're using is published as an npm package, it may include type declaration files as part of its distribution already.
|
||||
You can read the project's documentation to find out, or simply try importing the package and see if TypeScript is able to automatically resolve the types for you.
|
||||
|
||||
If you're a package author considering bundling type definitions with your package, you can read our guide on [bundling type definitions](/docs/handbook/declaration-files/publishing#including-declarations-in-your-npm-package).
|
||||
|
||||
### DefinitelyTyped / `@types`
|
||||
|
||||
The [DefinitelyTyped repository](https://github.com/DefinitelyTyped/DefinitelyTyped/) is a centralized repo storing declaration files for thousands of libraries.
|
||||
The vast majority of commonly-used libraries have declaration files available on DefinitelyTyped.
|
||||
|
||||
Definitions on DefinitelyTyped are also automatically published to npm under the `@types` scope.
|
||||
The name of the types package is always the same as the name of the underlying package itself.
|
||||
For example, if you installed the `react` npm package, you can install its corresponding types by running
|
||||
|
||||
```sh
|
||||
npm install --save-dev @types/react
|
||||
```
|
||||
|
||||
TypeScript automatically finds type definitions under `node_modules/@types`, so there's no other step needed to get these types available in your program.
|
||||
|
||||
### Your Own Definitions
|
||||
|
||||
In the uncommon event that a library didn't bundle its own types and didn't have a definition on DefinitelyTyped, you can write a declaration file yourself.
|
||||
See the appendix [Writing Declaration Files](/docs/handbook/declaration-files/introduction) for a guide.
|
||||
|
||||
If you want to silence warnings about a particular module without writing a declaration file, you can also quick declare the module as type `any` by putting an empty declaration for it in a `.d.ts` file in your project.
|
||||
For example, if you wanted to use a module named `some-untyped-module` without having definitions for it, you would write:
|
||||
|
||||
```ts
|
||||
declare module "some-untyped-module";
|
||||
```
|
||||
@@ -0,0 +1,63 @@
|
||||
---
|
||||
title: "Typeof Type Operator"
|
||||
description: "Using the typeof operator in type contexts."
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Typeof Type Operator.md"
|
||||
---
|
||||
|
||||
# Typeof Type Operator
|
||||
|
||||
## The `typeof` type operator
|
||||
|
||||
JavaScript already has a `typeof` operator you can use in an _expression_ context:
|
||||
|
||||
```ts
|
||||
// Prints "string"
|
||||
console.log(typeof "Hello world");
|
||||
```
|
||||
|
||||
TypeScript adds a `typeof` operator you can use in a _type_ context to refer to the _type_ of a variable or property:
|
||||
|
||||
```ts
|
||||
let s = "hello";
|
||||
let n: typeof s;
|
||||
```
|
||||
|
||||
This isn't very useful for basic types, but combined with other type operators, you can use `typeof` to conveniently express many patterns.
|
||||
For an example, let's start by looking at the predefined type `ReturnType<T>`.
|
||||
It takes a _function type_ and produces its return type:
|
||||
|
||||
```ts
|
||||
type Predicate = (x: unknown) => boolean;
|
||||
type K = ReturnType<Predicate>;
|
||||
```
|
||||
|
||||
If we try to use `ReturnType` on a function name, we see an instructive error:
|
||||
|
||||
```ts
|
||||
function f() {
|
||||
return { x: 10, y: 3 };
|
||||
}
|
||||
type P = ReturnType<f>;
|
||||
```
|
||||
|
||||
Remember that _values_ and _types_ aren't the same thing.
|
||||
To refer to the _type_ that the _value `f`_ has, we use `typeof`:
|
||||
|
||||
```ts
|
||||
function f() {
|
||||
return { x: 10, y: 3 };
|
||||
}
|
||||
type P = ReturnType<typeof f>;
|
||||
```
|
||||
|
||||
### Limitations
|
||||
|
||||
TypeScript intentionally limits the sorts of expressions you can use `typeof` on.
|
||||
|
||||
Specifically, it's only legal to use `typeof` on identifiers (i.e. variable names) or their properties.
|
||||
This helps avoid the confusing trap of writing code you think is executing, but isn't:
|
||||
|
||||
```ts
|
||||
// Meant to use = ReturnType<typeof msgbox>
|
||||
let shouldContinue: typeof msgbox("Are you sure you want to continue?");
|
||||
```
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
title: "Creating Types from Types"
|
||||
description: "An overview of the ways in which you can create more types from existing types."
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/_Creating Types from Types.md"
|
||||
---
|
||||
|
||||
# Creating Types from Types
|
||||
|
||||
TypeScript's type system is very powerful because it allows expressing types _in terms of other types_.
|
||||
|
||||
The simplest form of this idea is generics. Additionally, we have a wide variety of _type operators_ available to use.
|
||||
It's also possible to express types in terms of _values_ that we already have.
|
||||
|
||||
By combining various type operators, we can express complex operations and values in a succinct, maintainable way.
|
||||
In this section we'll cover ways to express a new type in terms of an existing type or value.
|
||||
|
||||
- [Generics](/docs/handbook/2/generics) - Types which take parameters
|
||||
- [Keyof Type Operator](/docs/handbook/2/keyof-types) - Using the `keyof` operator to create new types
|
||||
- [Typeof Type Operator](/docs/handbook/2/typeof-types) - Using the `typeof` operator to create new types
|
||||
- [Indexed Access Types](/docs/handbook/2/indexed-access-types) - Using `Type['a']` syntax to access a subset of a type
|
||||
- [Conditional Types](/docs/handbook/2/conditional-types) - Types which act like if statements in the type system
|
||||
- [Mapped Types](/docs/handbook/2/mapped-types) - Creating types by mapping each property in an existing type
|
||||
- [Template Literal Types](/docs/handbook/2/template-literal-types) - Mapped types which change properties via template literal strings
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
title: "Understanding Errors"
|
||||
description: "How to read TypeScript errors."
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Understanding Errors.md"
|
||||
---
|
||||
|
||||
# Understanding Errors
|
||||
|
||||
Whenever TypeScript finds an error, it tries to explain what went wrong in as much detail as possible.
|
||||
Because its type system is structural, this often means providing somewhat lengthy descriptions of where it found a problem.
|
||||
|
||||
## Terminology
|
||||
|
||||
There is some terminology you'll frequently see in error messages that is helpful to understand.
|
||||
|
||||
#### _assignable to_
|
||||
|
||||
TypeScript considers a type _assignable to_ another type if one is an acceptable substitute for the other.
|
||||
In other words, a `Cat` is _assignable to_ an `Animal` because a `Cat` is an acceptable substitute for an `Animal`.
|
||||
|
||||
As its name implies, this relationship is used to check the validity of an assignment `t = s;` by examining the types of `t` and `s`.
|
||||
It's also used to check most other places where two types interact.
|
||||
For example, when calling a function, each argument's type must be _assignable to_ parameter's declared type.
|
||||
|
||||
Informally, if you see `T is not assignable to S`, you can think of that as TypeScript saying "_`T` and `S` are not compatible"_.
|
||||
However, note that this is a _directional_ relationship: `S` being assignable to `T` does not imply that `T` is assignable to `S`.
|
||||
|
||||
## Examples
|
||||
|
||||
Let's look at some example error messages and understand what's going on.
|
||||
|
||||
### Error Elaborations
|
||||
|
||||
Each error starts with a leading message, sometimes followed by more sub-messages.
|
||||
You can think of each sub-message as answering a "why?" question about the message above it.
|
||||
Let's work through some examples to see how they work in practice.
|
||||
|
||||
Here's an example that produces an error message longer than the example itself:
|
||||
|
||||
```ts
|
||||
let a: { m: number[] };
|
||||
let b = { m: [""] };
|
||||
a = b;
|
||||
```
|
||||
|
||||
TypeScript found an error when checking the last line.
|
||||
Its logic for issuing an error follows from its logic for determining if the assignment is OK:
|
||||
|
||||
1. Is `b`'s type assignable to `a`'s? No. Why?
|
||||
2. Because the type of the `m` property is incompatible. Why?
|
||||
3. Because `b`'s `m` property (`string[]`) is not assignable to `a`'s `m` property (`number[]`). Why?
|
||||
4. Because one array's element type (`string`) is not assignable to the other (`number`)
|
||||
|
||||
### Extra Properties
|
||||
|
||||
```ts
|
||||
type A = { m: number };
|
||||
const a: A = { m: 10, n: "" };
|
||||
```
|
||||
|
||||
### Union Assignments
|
||||
|
||||
```ts
|
||||
type Thing = "none" | { name: string };
|
||||
|
||||
const a: Thing = { name: 0 };
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,14 @@
|
||||
---
|
||||
title: "Angular"
|
||||
description: "Using Angular with TypeScript"
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/tutorials/Angular.md"
|
||||
---
|
||||
|
||||
# Angular
|
||||
|
||||
Angular is a modern framework built entirely in TypeScript, and as a result, using TypeScript with Angular provides a seamless experience.
|
||||
|
||||
The Angular documentation not only supports TypeScript as a first-class citizen, but uses it as its primary language.
|
||||
With this in mind, [Angular's site](https://angular.io) will always be the most up-to-date reference for using Angular with TypeScript.
|
||||
|
||||
Check out the [quick start guide here](https://angular.io/docs/ts/latest/quickstart.html) to start learning Angular now!
|
||||
@@ -0,0 +1,216 @@
|
||||
---
|
||||
title: "ASP.NET Core"
|
||||
description: "Using TypeScript in ASP.NET Core"
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/tutorials/ASP.NET Core.md"
|
||||
---
|
||||
|
||||
# ASP.NET Core
|
||||
|
||||
## Install ASP.NET Core and TypeScript
|
||||
|
||||
First, install [ASP.NET Core](https://dotnet.microsoft.com/apps/aspnet) if you need it. This quick-start guide requires Visual Studio 2015 or 2017.
|
||||
|
||||
Next, if your version of Visual Studio does not already have the latest TypeScript, you can [install it](https://www.typescriptlang.org/index.html#download-links).
|
||||
|
||||
## Create a new project
|
||||
|
||||
1. Choose **File**
|
||||
2. Choose **New Project** (Ctrl + Shift + N)
|
||||
3. Search for **.NET Core** in the project search bar
|
||||
4. Select **ASP.NET Core Web Application** and press the _Next_ button
|
||||
|
||||

|
||||
|
||||
5. Name your project and solution. After select the _Create_ button
|
||||
|
||||

|
||||
|
||||
6. In the last window, select the **Empty** template and press the _Create_ button
|
||||
|
||||

|
||||
|
||||
Run the application and make sure that it works.
|
||||
|
||||

|
||||
|
||||
### Set up the server
|
||||
|
||||
Open **Dependencies > Manage NuGet Packages > Browse.** Search and install `Microsoft.AspNetCore.StaticFiles` and `Microsoft.TypeScript.MSBuild`:
|
||||
|
||||

|
||||
|
||||
Open up your `Startup.cs` file and edit your `Configure` function to look like this:
|
||||
|
||||
```cs
|
||||
public void Configure(IApplicationBuilder app, IHostEnvironment env)
|
||||
{
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
app.UseDeveloperExceptionPage();
|
||||
}
|
||||
|
||||
app.UseDefaultFiles();
|
||||
app.UseStaticFiles();
|
||||
}
|
||||
```
|
||||
|
||||
You may need to restart VS for the red squiggly lines below `UseDefaultFiles` and `UseStaticFiles` to disappear.
|
||||
|
||||
## Add TypeScript
|
||||
|
||||
Next we will add a new folder and call it `scripts`.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## Add TypeScript code
|
||||
|
||||
Right click on `scripts` and click **New Item**. Then choose **TypeScript File** and name the file `app.ts`
|
||||
|
||||

|
||||
|
||||
### Add example code
|
||||
|
||||
Add the following code to the `app.ts` file.
|
||||
|
||||
```ts
|
||||
function sayHello() {
|
||||
const compiler = (document.getElementById("compiler") as HTMLInputElement)
|
||||
.value;
|
||||
const framework = (document.getElementById("framework") as HTMLInputElement)
|
||||
.value;
|
||||
return `Hello from ${compiler} and ${framework}!`;
|
||||
}
|
||||
```
|
||||
|
||||
## Set up the build
|
||||
|
||||
_Configure the TypeScript compiler_
|
||||
|
||||
First we need to tell TypeScript how to build. Right click on `scripts` and click **New Item**. Then choose **TypeScript Configuration File** and use the default name of `tsconfig.json`
|
||||
|
||||

|
||||
|
||||
Replace the contents of the `tsconfig.json` file with:
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"noEmitOnError": true,
|
||||
"noImplicitAny": true,
|
||||
"sourceMap": true,
|
||||
"target": "es6"
|
||||
},
|
||||
"files": ["./app.ts"],
|
||||
"compileOnSave": true
|
||||
}
|
||||
```
|
||||
|
||||
- [`noEmitOnError`](https://www.typescriptlang.org/tsconfig#noEmitOnError) : Do not emit outputs if any errors were reported.
|
||||
- [`noImplicitAny`](https://www.typescriptlang.org/tsconfig#noImplicitAny) : Raise error on expressions and declarations with an implied `any` type.
|
||||
- [`sourceMap`](https://www.typescriptlang.org/tsconfig#sourceMap) : Generates corresponding `.map` file.
|
||||
- [`target`](https://www.typescriptlang.org/tsconfig#target) : Specify ECMAScript target version.
|
||||
|
||||
Note: `"ESNext"` targets latest supported
|
||||
|
||||
[`noImplicitAny`](https://www.typescriptlang.org/tsconfig#noImplicitAny) is good idea whenever you’re writing new code — you can make sure that you don’t write any untyped code by mistake. `"compileOnSave"` makes it easy to update your code in a running web app.
|
||||
|
||||
### _Set up NPM_
|
||||
|
||||
We need to setup NPM so that JavaScript packages can be downloaded. Right click on the project and select **New Item**. Then choose **NPM Configuration File** and use the default name of `package.json`.
|
||||
|
||||

|
||||
|
||||
Inside the `"devDependencies"` section of the `package.json` file, add _gulp_ and _del_
|
||||
|
||||
```json
|
||||
"devDependencies": {
|
||||
"gulp": "4.0.2",
|
||||
"del": "5.1.0"
|
||||
}
|
||||
```
|
||||
|
||||
Visual Studio should start installing gulp and del as soon as you save the file. If not, right-click package.json and then Restore Packages.
|
||||
|
||||
After you should see an `npm` folder in your solution explorer
|
||||
|
||||

|
||||
|
||||
### _Set up gulp_
|
||||
|
||||
Right click on the project and click **New Item**. Then choose **JavaScript File** and use the name of `gulpfile.js`
|
||||
|
||||
```js
|
||||
/// <binding AfterBuild='default' Clean='clean' />
|
||||
/*
|
||||
This file is the main entry point for defining Gulp tasks and using Gulp plugins.
|
||||
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
|
||||
*/
|
||||
|
||||
var gulp = require("gulp");
|
||||
var del = require("del");
|
||||
|
||||
var paths = {
|
||||
scripts: ["scripts/**/*.js", "scripts/**/*.ts", "scripts/**/*.map"],
|
||||
};
|
||||
|
||||
gulp.task("clean", function () {
|
||||
return del(["wwwroot/scripts/**/*"]);
|
||||
});
|
||||
|
||||
gulp.task("default", function (done) {
|
||||
gulp.src(paths.scripts).pipe(gulp.dest("wwwroot/scripts"));
|
||||
done();
|
||||
});
|
||||
```
|
||||
|
||||
The first line tells Visual Studio to run the task ‘default’ after the build finishes. It will also run the ‘clean’ task when you ask Visual Studio to clean the build.
|
||||
|
||||
Now right-click on `gulpfile.js` and click Task Runner Explorer.
|
||||
|
||||

|
||||
|
||||
If ‘default’ and ‘clean’ tasks don’t show up, refresh the explorer:
|
||||
|
||||

|
||||
|
||||
## Write a HTML page
|
||||
|
||||
Right click on the `wwwroot` folder (if you don't see the folder try building the project) and add a New Item named `index.html` inside. Use the following code for `index.html`
|
||||
|
||||
```
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<script src="scripts/app.js"></script>
|
||||
<title></title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="message"></div>
|
||||
<div>
|
||||
Compiler: <input id="compiler" value="TypeScript" onkeyup="document.getElementById('message').innerText = sayHello()" /><br />
|
||||
Framework: <input id="framework" value="ASP.NET" onkeyup="document.getElementById('message').innerText = sayHello()" />
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## Test
|
||||
|
||||
1. Run the project
|
||||
2. As you type on the boxes you should see the message appear/change!
|
||||
|
||||

|
||||
|
||||
## Debug
|
||||
|
||||
1. In Edge, press F12 and click the Debugger tab.
|
||||
2. Look in the first localhost folder, then scripts/app.ts
|
||||
3. Put a breakpoint on the line with return.
|
||||
4. Type in the boxes and confirm that the breakpoint hits in TypeScript code and that inspection works correctly.
|
||||
|
||||

|
||||
|
||||
Congrats you've built your own .NET Core project with a TypeScript frontend.
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: "Using Babel with TypeScript"
|
||||
description: "How to create a hybrid Babel + TypeScript project"
|
||||
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/tutorials/Babel with TypeScript.md"
|
||||
---
|
||||
|
||||
# Using Babel with TypeScript
|
||||
|
||||
## Babel vs `tsc` for TypeScript
|
||||
|
||||
When making a modern JavaScript project, you might ask yourself what is the right way to convert files from TypeScript to JavaScript?
|
||||
|
||||
A lot of the time the answer is _"it depends"_, or _"someone may have decided for you"_ depending on the project. If you are building your project with an existing framework like [tsdx](https://tsdx.io), [Angular](https://angular.io/), [NestJS](https://nestjs.com/) or any framework mentioned in the [Getting Started](https://www.typescriptlang.org/docs) then this decision is handled for you.
|
||||
|
||||
However, a useful heuristic could be:
|
||||
|
||||
- Is your build output mostly the same as your source input files? Use `tsc`
|
||||
- Do you need a build pipeline with multiple potential outputs? Use `babel` for transpiling and `tsc` for type checking
|
||||
|
||||
## Babel for transpiling, `tsc` for types
|
||||
|
||||
This is a common pattern for projects with existing build infrastructure which may have been ported from a JavaScript codebase to TypeScript.
|
||||
|
||||
This technique is a hybrid approach, using Babel's [preset-typescript](https://babeljs.io/docs/en/babel-preset-typescript) to generate your JS files, and then using TypeScript to do type checking and `.d.ts` file generation.
|
||||
|
||||
By using babel's support for TypeScript, you get the ability to work with existing build pipelines and are more likely to have a faster JS emit time because Babel does not type check your code.
|
||||
|
||||
### Type Checking and d.ts file generation
|
||||
|
||||
The downside to using babel is that you don't get type checking during the transition from TS to JS. This can mean that type errors which you miss in your editor could sneak through into production code.
|
||||
|
||||
In addition to that, Babel cannot create `.d.ts` files for your TypeScript which can make it harder to work with your project if it is a library.
|
||||
|
||||
To fix these issues, you would probably want to set up a command to type check your project using TSC. This likely means duplicating some of your babel config into a corresponding [`tsconfig.json`](https://www.typescriptlang.org/tsconfig) and ensuring these flags are enabled:
|
||||
|
||||
```json
|
||||
"compilerOptions": {
|
||||
// Ensure that .d.ts files are created by tsc, but not .js files
|
||||
"declaration": true,
|
||||
"emitDeclarationOnly": true,
|
||||
// Ensure that Babel can safely transpile files in the TypeScript project
|
||||
"isolatedModules": true
|
||||
}
|
||||
```
|
||||
|
||||
For more information on these flags:
|
||||
|
||||
- [`isolatedModules`](https://www.typescriptlang.org/tsconfig#isolatedModules)
|
||||
- [`declaration`](https://www.typescriptlang.org/tsconfig#declaration), [`emitDeclarationOnly`](https://www.typescriptlang.org/tsconfig#emitDeclarationOnly)
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user