TypeScriptã«ã¯anyã使ããªããã注æãã¦ãåæ¤æ»ãç¡å¹åããåå®å ¨æ§ã失ããããã¿ã¼ã³ãããã¤ããããä¸ã«ã¯è´å½çãªãã®ãåå¨ãããä»åã¯ãã®ãã¿ã¼ã³ãããã¤ãç´¹ä»ããã
ã³ã¼ã«ããã¯ã®voidæ»ãå¤å
ã³ã¼ã«ããã¯ã®voidæ»ãå¤åã¯ãã¹ã¦ã®åãåãå ¥ããããvoidå === anyåã¨ãªãã
function f(cb: (a: number) => void): void { return cb(0); } function g(a: number): number { return a; } f(g);
ãã®ããvoidåã®å¤ã¯voidæ¼ç®åã使ç¨ãã¦å³åº§ã«å¼·å¶çã«voidåã«å¤æããªããã°ãªããªãã
void f(g);
ããã§ã¯æé ãã
function f(cb: (a: number) => void): void { return void cb(0); }
ããã§å¤æããã
ã³ã¼ã«ããã¯ã®ãã©ã¡ã¼ã¿æ°
ã³ã¼ã«ããã¯ã®ãã©ã¡ã¼ã¿æ°ã®ä¸è¶³ã¯åã¨ã©ã¼ã«ãªããæ¤åºã§ããªãã
type F = (cb: (a: number, b: string) => number) => number; type G = (cb: (a: number) => number) => number; var f: F = <G>((cb: (a: number) => number) => cb(0)); f((a, b) => a + b.length);
ãããåé¿ããæ¹æ³ã¯ãªããTypeScript 3.3ã¾ã§ã«ä¿®æ£æ¸ã¿ã
å ±å¤ã»åå¤
interface A { x: string; } interface B { x: string; y: string; } const fb = (fa: (a: A) => void) => fa({x: 'x'}); const fa= (b: B) => alert(b.y); fb(fa);
ã¾ããããã¯ä»æ¹ãªãã ãããã
Genericå
TypeScriptã®åæ¤æ»ã¯åºæ¬çã«æ§é åã®ç §åã§ãããåãã©ã¡ã¼ã¿ã¯ç §åã®å¯¾è±¡ã¨ãªãæ§é ã«å«ã¾ãã¦ããªããããæ§é ã«åæ ãããªãåãã©ã¡ã¼ã¿ã®åã¯ç¡è¦ãããã
class C<T extends Foo | Bar> { constructor(d) { d.cmd(); } } class Foo { f; cmd() { return this; } } class Bar { b; cmd() { return this; } } var c: C<Foo> = new C<Bar>(new Bar());
ãã®ããåãã©ã¡ã¼ã¿ã®ã¿ã§å®çµããç´ç²ãªå¹½éåã«ããåæ¤æ»ãè¡ããããã¨ãã¦ã失æããã
class C<T> { } var c: C<number> = new C<string>();
ãããåé¿ããã«ã¯åãã©ã¡ã¼ã¿ã§åãåã£ãåãããããã£ãã¡ã½ããã§æã£ã¦æ§é åã«åæ ãããªããã°ãªããªãã
class C<T> { c: T; } var c: C<number> = new C<string>();
ãã®ã»ããprivate/protectedã¢ã¯ã»ã¹ä¿®é£¾åã使ç¨ããã¨ã¯ã©ã¹ãå ¬ç§°åã¨ãªãåãä¸æã«èå¥ããã(ç¶æ¿ã¯ã©ã¹ã®åãé¤ã)ã
Genericåå®ç¾©
TypeScriptãããã©ã«ãã§å®ç¾©ãã¦ããããã¤ãã®åã§ã¯ãã®æ§è³ªã®ããè´å½çãªä¸æ´åãè¦è½ã¨ãå¯è½æ§ãããã
var s: PromiseLike<number | string> = <PromiseLike<string>>null; var n: PromiseLike<number> = <PromiseLike<number | string>>s;
ã©ãã ãå³æ ¼ã«åãå®ã£ã¦ããä¸è¨ã®ããã«æ°å¤ã®ã¿ãè¿ãåãæååãè¿ãããã«ãªãä¸æ£ãªä»£å ¥ãå¯è½ã§ããã åã«ãã£ã¦ã¯ä¸æ´åãæ¤åºããã®ã§ä¸æ£ã«ä»£å ¥å¯è½ãªåãå³åº§ã«è¦åãããã¨ã¯é£ããã
var s: ArrayLike<number | string> = <ArrayLike<string>>null; var n: ArrayLike<number> = <ArrayLike<number | string>>s;
ãã®ä¸æ´åãé²ãã«ã¯ã¤ã³ã¿ã¼ãã§ã¤ã¹ãæ¡å¼µãã¦å ã»ã©ã¨åæ§åãã©ã¡ã¼ã¿ãæ§é ã«è½ã¨ãã°ããã
interface PromiseLike<T> { _?: T; }
import/exportæãå«ããã¨æ°è¦ã®åå®ç¾©ã¨ãªãããå«ãªããã¨ã æ¡å¼µãè¡ã£ã¦ãå¤é¨ããã¯æ¡å¼µãå«ã¾ãªã.d.tsãã¡ã¤ã«ã ããåç §ãããã°æ¡å¼µãé è½ã§ããã®ã§å¤é¨ã®åå®ç¾©ãæ±æããã競åããããããã¨ã¯ãªãã
TypeScriptã§ã¯ãã®ç¨®ã®ä¸æ´åã«ãããã°ãé²ãããä¸è¨ã®ãããªå®£è¨ããã¾ããªãã®ããã«æ¯å追å ãã¦ããå¿
è¦ãããã ãããTypeScript 3.3ã¾ã§ã«ä¿®æ£æ¸ã¿ã
ã¾ã¨ã
åããã£ã¦ãã®ã«å¤ãªå¤ãå ¥ããã°ã«è¦ãã¿ãããªãã£ããããã«æ¸ãããã¿ã¼ã³ã¨å¯¾å¦æ³ãéçºã¡ã³ãã¼ã®TypeScript使ç¨è å ¨å¡ã«å¨ç¥ãããã¨ããå§ãããã