微信公众号
扫描关注微信公众号

什么是 `keyof` 和 `typeof` 操作符?

原创 来源:博客站 阅读 0 03月18日 07:00 听全文 分类:Typescript系列

keyoftypeof 是 TypeScript 中的两个重要操作符,它们用于在类型系统中获取类型信息。以下是它们的详细解释和使用示例:

keyof 操作符

keyof 操作符用于获取对象类型的所有键(属性名)的联合类型。它通常用于创建与对象属性相关的类型。

语法

type Keys = keyof T;

其中 T 是一个对象类型。

示例

以下是一个简单的 keyof 操作符示例,展示了如何获取对象类型的所有键:

interface Person {
    name: string;
    age: number;
    location: string;
}

type PersonKeys = keyof Person; // "name" | "age" | "location"

function getProperty(obj: Person, key: PersonKeys) {
    return obj[key];
}

const person: Person = {
    name: "Alice",
    age: 25,
    location: "New York"
};

const name = getProperty(person, "name"); // "Alice"
const age = getProperty(person, "age"); // 25
const location = getProperty(person, "location"); // "New York"

在这个例子中,PersonKeys 类型是 "name" | "age" | "location",表示 Person 接口的所有键的联合类型。

typeof 操作符

typeof 操作符用于获取变量或表达式的类型。它通常用于获取值的类型,并在类型注解中使用。

语法

type Type = typeof value;

其中 value 是一个变量或表达式。

示例

以下是一个简单的 typeof 操作符示例,展示了如何获取变量的类型:

const message = "Hello, world!";
type MessageType = typeof message; // string

const numbers = [1, 2, 3];
type NumbersType = typeof numbers; // number[]

function greet(name: string): string {
    return `Hello, ${name}!`;
}

type GreetFunctionType = typeof greet; // (name: string) => string

在这个例子中,MessageTypestring 类型,NumbersTypenumber[] 类型,GreetFunctionType(name: string) => string 类型。

keyoftypeof 的结合使用

keyoftypeof 可以结合使用,以获取对象的所有键的联合类型。

示例

以下是一个结合使用 keyoftypeof 的示例,展示了如何获取对象的所有键的联合类型:

const person = {
    name: "Alice",
    age: 25,
    location: "New York"
};

type PersonKeys = keyof typeof person; // "name" | "age" | "location"

function getProperty(obj: typeof person, key: PersonKeys) {
    return obj[key];
}

const name = getProperty(person, "name"); // "Alice"
const age = getProperty(person, "age"); // 25
const location = getProperty(person, "location"); // "New York"

在这个例子中,PersonKeys 类型是 "name" | "age" | "location",表示 person 对象的所有键的联合类型。

总结

  • keyof 操作符:用于获取对象类型的所有键的联合类型。
  • typeof 操作符:用于获取变量或表达式的类型。

理解 keyoftypeof 操作符的使用场景和语法,可以帮助你更好地利用 TypeScript 的类型系统,编写出更灵活和类型安全的代码。

- - - - - - - 剩余部分未读 - - - - - - -
扫描关注微信公众号获取验证码,阅读全文
你也可以查看我的公众号文章,阅读全文
你还可以登录,阅读全文
内容由AI生成仅供参考和学习交流,请勿使用于商业用途。
出处地址:http://www.07sucai.com/tech/706.html,如若转载请注明原文及出处。
版权声明:本文来源地址若非本站均为转载,若侵害到您的权利,请及时联系我们,我们会在第一时间进行处理。
>