xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

TypeScript in operator All In One

TypeScript in operator All In One

image

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;
}

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#unlisted-property-narrowing-with-the-in-operator

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, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-01-28 15:34  xgqfrms  阅读(211)  评论(3编辑  收藏  举报