简体   繁体   English

如何从打字稿中的接口对象设置类型?

[英]How to set type from a object of interface in typescript?

Below is my code 下面是我的代码

interface platformItem {
    Result: {
         name: string;
         age: number;
    };
}

const man: platformItem.Result;

The vscode will show warning which is no export member from platformItem, seems I can not use platformItem.result. vscode将显示警告,提示该用户不是platformItem的导出成员,似乎无法使用platformItem.result。

在vscode platformItem['Result']上为我工作

Here are three different approaches. 这是三种不同的方法。 Playground 操场

Indexed access 索引访问

interface platformItem {
    Result: {
         name: string;
         age: number;
    };
}

 const man: platformItem["Result"] = { name: "Max Power", age: 30 };

Type Aliases 类型别名

type Man = {
    name: string;
    age: number;
};

interface platformItem {
    Result: Man;
}

const man: Man = { name: "Max Power", age: 30 };

Declaration Merging 声明合并

namespace platformItem {
    export type Result = {
        name: string;
        age: number;
    };
}
interface platformItem {
    Result: platformItem.Result;
}

const man: platformItem.Result = { name: "Max Power", age: 30 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 打字稿:从对象创建接口或最窄的类型 - Typescript: Create an interface or the narrowest type from an Object Typescript:如何将类型设置为界面的键 - Typescript: how to set type as a key of interface 如何在TypeScript中动态扩展对象的接口或类型? - How to dynamically extend the interface or type of an object in TypeScript? 如何在TypeScript中为对象元素指定接口类型? - How to specify an interface type to an object element in TypeScript? TypeScript:如何将接口限制为类型对象的变量? - TypeScript: How to limit interface to variable of type object? 如何为 object 分配 const 类型,同时从 Typescript 中的其他类型或接口扩展它? - How to assign an object a const type while extend it from some other type or interface in Typescript? TypeScript:从 object 内容隐式推断通用接口的 object 类型 - TypeScript: Infer type of object of generic interface implicitly from object content TypeScript:如何合并来自另一个界面的对象? - TypeScript: How to merge an object from another interface? 如何在typescript对象接口中键入字符串作为Object属性键? - How to type a string as an Object property-key in a typescript Object interface? TypeScript:如何使用属性扩展从其他接口检索的类型的接口 - TypeScript: interface how to extends a type that retrieved from other interface with a property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM