ES2022 㨠TypeScript 4.5 ã«å
¥ããã©ã¤ãã¼ããã£ã¼ã«ãã®ããã® in æ¼ç®åã«ã¤ãã¦
Published on
2021å¹´7æã«è¡ããã TC39 ãã¼ãã£ã³ã°ã§ Ergonomic brand checks for Private Fields ã¨ãããããã¼ã¶ã«ã Stage 4 ã«ãªãã¾ããã ãã®ãããã¼ã¶ã«ã¯ãES2022 ã«å«ã¾ããäºå®ã§ããã¾ããTypeScript 4.5 ã«ãå«ã¾ããäºå®ã§ãã
ãã®è¨äºã§ã¯ãErgonomic brand checks for Private Fields ã«ã¤ãã¦è§£èª¬ãã¾ãã
æ¦è¦
Ergonomic brand checks for Private Fields ã¯ãin
æ¼ç®åã使ã£ããã©ã¤ãã¼ããã£ã¼ã«ãã®æç¡ã®å¤å®ãå¯è½ã«ãããããã¼ã¶ã«ã§ãã
ç¾å¨ã® in
æ¼ç®å
in
æ¼ç®åã¯ããªãã¸ã§ã¯ããç¹å®ã®ååã®ããããã£ãæã£ã¦ãããã©ãããå¤å®ããããã®äºé
æ¼ç®åã§ãã
左辺ã«ããããã£ã®ååãå³è¾ºã«ãªãã¸ã§ã¯ããåãåãã¾ãã
const obj = { prop1: 1 };
console.log("prop1" in obj); // true
æ°ãã in
æ¼ç®å
Ergonomic brand checks for Private Fields ã§ã¯ããã® in
æ¼ç®åãæ¡å¼µãã左辺㫠Private Identifier ãåããããã«ãªãã¾ãã
Private Identifier 㯠#foo
ã®ãããªå½¢ãããç¹å¥ãªèå¥åã§ãã¯ã©ã¹ã®ãã©ã¤ãã¼ããã£ã¼ã«ãã表ç¾ããã®ã«ä½¿ããã¾ãã
ãã¨ãã°ã次ã®ã³ã¼ãã§ã¯ã¯ã©ã¹ Foo
ã¯ã#prop1
ã¨ãããã©ã¤ãã¼ããã£ã¼ã«ããæã¡ã¾ãã
ãã®ã¨ã #prop1
㯠Private Identifier ã§ãã
class Foo {
#prop1;
}
æ¡å¼µããã in
æ¼ç®åã§ã¯ã次ã®ããã«ãã¦ãªãã¸ã§ã¯ãã«ãã©ã¤ãã¼ããã£ã¼ã«ããå«ã¾ãããã©ããããã§ãã¯ã§ãã¾ãã
#prop1 in obj
ãããããã©ã¤ãã¼ããã£ã¼ã«ãã¯ãã©ã¤ãã¼ããªã®ã§ä¸è¨ã®ã³ã¼ãã¯ãã®ãã£ã¼ã«ããæã¤ã¯ã©ã¹ã®ä¸ã§ã®ã¿ä½¿ããã¨ãã§ãã¾ãã
ã¤ã¾ãã次ã®ããã«ã¯ã©ã¹ã®å¤ã§ãã©ã¤ãã¼ããã£ã¼ã«ãã«å¯¾ã㦠in
ã使ãã¨ã¨ã©ã¼ã«ãªãã¾ãã
class Foo {
#prop1;
}
console.log(#prop1 in new Foo());
// Uncaught SyntaxError: Private field '#prop1' must be declared in an enclosing class
ãããã次ã®ãããªã³ã¼ãã¯ã¨ã©ã¼ã«ãªãã¾ãããã¡ã½ãã foo
ã¯ã¯ã©ã¹ Foo
ã®ä¸ã«ããã®ã§ãPrivate Identifier ã§ãã #foo
ã in
æ¼ç®åã®å·¦è¾ºã¨ãã¦ä½¿ããã¨ãã§ãã¾ãã
ããã¦ããã® foo
ã®ä¸ã§ this
㯠Foo
ã®ã¤ã³ã¹ã¿ã³ã¹ã§ãããããã«ã¯å½ç¶ #prop1
ã¨ãããã©ã¤ãã¼ãããããã£ãåå¨ããã®ã§ã#prop1 in this
ã®çµæ㯠true
ã«ãªãã¾ãã
class Foo {
#prop1;
foo() {
return #prop1 in this;
}
}
console.log(new Foo().foo()); // true
ã¢ããã¼ã·ã§ã³
åå¨ããªããã©ã¤ãã¼ããã£ã¼ã«ãã«ã¢ã¯ã»ã¹ããã¨ãå®è¡æã¨ã©ã¼ãçºçãã¾ãã
ãã®æå㨠try / catch ãçµã¿åããã¦ã次ã®ããã«ãã¦ãªãã¸ã§ã¯ãã®ã¯ã©ã¹ãå¤å®ã§ãã¾ãã
class Foo {
#brand;
static isFoo(obj) {
try {
obj.#brand;
return true;
} catch {
return false;
}
}
}
obj.#brand
ã«ã¢ã¯ã»ã¹ããã¨ããobj
ã Foo ã®ã¤ã³ã¹ã¿ã³ã¹ã§ãªãå ´åãå®è¡æã¨ã©ã¼ãçºçã catch
ã«å
¥ã false
ãè¿ããã¾ãã
ãã®ããã«ãã¦ããããªãã¸ã§ã¯ããFoo
ã®ã¤ã³ã¹ã¿ã³ã¹ã§ããããæ¤è¨¼ããã¹ã¿ãã£ãã¯ã¡ã½ãããä½ãã¾ãã
ã§ããããã®ãã¿ã¼ã³ã¯åé·ã§ããin
æ¼ç®åã使ãã°ãã£ã¨çãæ¸ãã¾ãã
class Foo {
#brand;
static isFoo(obj) {
return #brand in obj;
}
}
ãããããã®ãããã¼ã¶ã«ã®ä¸»ãªã¢ããã¼ã·ã§ã³ã§ãã
instanceof
æ¼ç®åãåºæ¬çã«ã¯ãã®ç®çã®ããã«ä½¿ãã¾ããããã instanceof
æ¼ç®åã¯ãããã¿ã¤ãã«ä¾åããã®ã§ããããã¿ã¤ããæ¸ãæãããã¨ã§ãã®æåãå¤æ´ã§ãã¾ãã
次ã®ä¾ã§ã¯ã obj
㯠Foo
ã®ã¤ã³ã¹ã¿ã³ã¹ã§ã¯ããã¾ããããå¾ãããããã¿ã¤ããæ¸ãæãã¦ããã®ã§ obj instanceof Foo
㯠true
ã«ãªã£ã¦ãã¾ãã
class Foo {}
const foo = new Foo();
const obj = {};
Object.setPrototypeOf(obj, foo);
console.log(obj instanceof Foo); // true
ã¾ããSymbol.hasInstance ã使ã£ã¦ instanceof
ã®æåãå¤æ´ãããã¨ãå¯è½ã§ãã
ãªã®ã§ãããå®å
¨ã«ãªãã¸ã§ã¯ãã®ãã¨ã«ãªã£ãã¯ã©ã¹ãæ¤è¨¼ãããå ´å㯠in
æ¼ç®åã使ãã¨è¯ãã§ãããã
åèãªã³ã¯
è¨äºã«é¢ããå ±åãªã©ã¯ãã¡ããã