TypeScript in operator All In One
TypeScript in operator All In One
JavaScript in
Operator
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#in
TypeScript 4.9 in
interface Context {
packageJSON: unknown;
}
function tryGetPackageName(context: Context): string | undefined {
const packageJSON = context.packageJSON;
// Check to see if we have an object.
if (packageJSON && typeof packageJSON === "object") {
// Check to see if it has a string name property.
if ("name" in packageJSON && typeof packageJSON.name === "string") {
// Just works!
return packageJSON.name;
}
}
return undefined;
}
Record
const sym = Symbol();
function f1(x: unknown) {
if (x && typeof x === "object" && "a" in x && 1 in x && sym in x) {
x; // Record<"a", unknown> & Record<1, unknown> & Record<typeof sym, unknown>
x.a; // Ok
x[1]; // Ok
x[sym]; // Ok
}
}
function f2(x: { a: string } | { b: string }) {
if ("a" in x) {
x; // { a: string }
}
else if ("b" in x) {
x; // { b: string }
}
else {
x; // never
}
}
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
// map props type
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
cats.boris;
// const cats: Record<CatName, CatInfo>
// (property) boris: CatInfo
https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type
demos
interface Person {
name: string;
age: number;
}
type Partial<T> = {
// K will be each key of T
[K in keyof T]?: T[K];
}
type PersonPartial = Partial<Person>;
// same as
// type PersonPartial = { name?: string; age?: number; }
Mapped Types
https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types
https://www.typescriptlang.org/docs/handbook/2/mapped-types.html
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17070417.html
未经授权禁止转载,违者必究!