打字稿定义从对象中提取的值

时间:2021-04-06 12:35:22

标签: typescript

我有这样的 javascript 代码。

const { a, b, c } = {
    a : "hello",
    b : "stackoverflow",
    c : "it's greate"
};

我想把它做成打字稿。有什么解决办法吗?

2 个答案:

答案 0 :(得分:0)

正如Captain-yossarian 提到的,这也适用于打字稿。我建议您从基础开始 - 这意味着只需为您当前的“黑匣子”对象准备一个类型(= a 可以是字符串、数组等):

interface SomeType {
    a: string;
    b: string;
    c: number;
}

const { a, b, c }: SomeType = {
    a : "hello",
    b : "stackoverflow",
    c : "it's greate" // This will not work because c has to be a number!
};

然后您的 IDE/编辑器就会知道,ab 是字符串,c 应该是一个数字(并且还会抛出错误,因为 c 不是一个号码)。当处理更多数据和更大的代码库时,这将变得至关重要。 我真的可以推荐这个(官方)指南:https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html

答案 1 :(得分:0)

它已经是一个 TS 有效代码!您可以使用类型以获得更好的代码。

export type Something = {
   a: string,
   b: number,
   c: Custom
}

const { a, b, c }: Something = {
    a : "hello",
    b : 3,
    c : {}
};