住讜讙讬 诪讞专讜讝讜转 转讘谞讬转 讻转讘

讻讬爪讚 诇爪诪爪诐 住讜讙讬 诪讞专讜讝讜转 讘讗诪爪注讜转 诪谞讙谞讜谉 诪讞专讜讝转 讛转讘谞讬讜转

诪讛诐 住讜讙讬诐 诪讬诇讜诇讬讬诐 砖诇 转讘谞讬转

诪讗讝 Typescript 4.1, 讗转讛 讬讻讜诇 诇砖驻专 诪砖诪注讜转讬转 讗转 讛讛拽诇讚讜转 注讘讜专 讛诪讞专讜讝讜转 砖诇讱. 专拽 讻讚讬 诇住讻诐 讘诪讛讬专讜转, 讘- Typescript 转讜讻诇讜 诇讛讙讚讬专 诪讛 砖诪讻讜谞讛 "讟讬驻讜住讬诐 诪讬诇讜诇讬讬诐". 讘诪拽讜诐 诇讛讙讚讬专 专拽 诪砖转谞讛 讻诪讞专讜讝转, 讗转讛 讬讻讜诇 诇爪诪爪诐 讗转 讛住讜讙 诇拽讘讜爪转 诪讞专讜讝讜转 住驻爪讬驻讬转 讛诪讜转专转.

// Define a mutable string as 'Literal Type'.
let key: "name" | "department" = "name";

// This works, as 'department' is part of the type.
key = "department";
// Won't work, as it's not define in the union type.
key = "company";

// Of course, the same applies for functions.
function getKey(): "name" | "department" {
  return Math.random() <= 0.5 ? "name" : "department";
}

讛讞诇 诪- Typescript 4.1, 讛诪讜砖讙 讛讝讛 驻讜转讞 注讜讚 讬讜转专. 注诇 讬讚讬 诇拽讬讞转 "诪讞专讜讝讜转 诪讬诇讜诇讬讜转 转讘谞讬讜转" 诪- Javascript 讻讛砖专讗讛, 转讜讻诇 诇讛讞讬诇 讗转 讗讜转讜 转讞讘讬专 诇住讜讙讬诐 讛诪讬诇讜诇讬讬诐 砖诇讱 讘- Typescript. 讛讛讘讚诇 讛注讬拽专讬 讛讜讗 砖注诐 "住讜讙讬诐 诪讬诇讜诇讬讬诐 转讘谞讬转讬讬诐", 讗转讛 诪专讜讜讬讞 讛专讘讛 讬讜转专 讙诪讬砖讜转, 诪讻讬讜讜谉 砖讛住讜讙 注爪诪讜 讬讻讜诇 诇拽讘诇 驻专诪讟专讬诐 诇爪讜专讛 讝讜 - 讛专注讬讜谉 讚讜诪讛 诇讙谞专讬讜转, 讗讱 砖讜谞讛 讘诪拽爪转 讘讻讱 砖讛讜讗 讚讜专砖 注专讻讬诐 住驻爪讬驻讬讬诐.

// Define a Literal Type
type State = "ready";

// Nice, isn't it? As in Javascript's 
// 'template literal strings', we can
// reuse the same syntax for TS.
//
// The create type here is now 'Key-ready'.
type Key = `key-${State}`;
// This of course works for union types as well.
// Let's take these non-descriptive types for a 
// quick demo:
type GraphState = "sleep" | "ready" | "error";
type MachineState = "booting" | "running";

// And here's the 'template literal type':
type EntityState = `ES-${GraphState | MachineState}`;

// The possible combinations therefore 
// work out like this:
//
// type EntityState = 'ES-sleep' 
//  | 'ES-ready'
//  | 'ES-error'
//  | 'ES-booting'
//  | 'ES-running'

讬砖 注讜讚 讬讜转专 注诐 Typescript 4.3

讻砖讗谞讬 讻讜转讘 讗转 讝讛, 诪讜注诪讚 讛砖讞专讜专 诇- Typescript 4.3 砖讜讞专专, 砖讻讜诇诇 砖讬驻讜专讬诐 谞讜住驻讬诐 讘住讜讙讬诐 诪讬诇讜诇讬讬诐 转讘谞讬转讬讬诐.

诪注专讻转 讛住讜讙讬诐 讻注转 讚讬谞诪讬转 注讜讚 讬讜转专 讜讬讻讜诇讛 诇讛住讬拽 讟讜讘 讬讜转专 讗转 讛住讜讙讬诐 讛谞讻讜谞讬诐 注讘讜专讱. 砖讬谞讜讬讬诐 讗讞专讜谞讬诐 讗诇讛 诪讘砖讬诇讬诐 讗转 住讜讙 诪讞专讜讝转 讛转讘谞讬转.

// This example is taken 1:1 from 
// Typescript's 4.3 announcement.
// Please check out the link in the
// addendum to see all examples!

declare let s: string;
declare function f<T extends string>(x: T): T;

// Previously: string
// Now       : `hello-${string}`
let x2 = f(`hello ${s}`);

住讬讻讜诐

讻驻讬 砖专讗讬转诐, Typescript 讛讬讗 砖驻讛 讻讛 注讜爪诪转讬转 讘讻诇 诪讛 砖拽砖讜专 诇讛讙讚专转 住讜讙讬诐 讚讬谞诪讬讬诐. 讝讛 谞讻讜谉 讘诪讬讜讞讚 诇讙讘讬 住讜讙讬诐 诪讘讜住住讬 诪讞专讜讝讜转. 注诐 讛砖讬谞讜讬讬诐 讛讗讞专讜谞讬诐 讘讙专住讛 4.3, 诪注专讻转 讛住讜讙讬诐 讬讻讜诇讛 诇讛住讬拽 讟讜讘 讬讜转专 讗转 讛住讜讙讬诐 讛谞讻讜谞讬诐 诪转诪讬讚, 诪讛 砖讛讜驻讱 讗转 讛注讘讜讚讛 注诐 Typescript 诇住转诐 转注谞讜讙.

讛爪注讜转

拽砖讜专

谞住驻讞