javascript - 将 typescript 类型和接口合二为一
问题描述
我们正在尝试为下面的 JSON 文件创建一个 TypeScript 定义。
应用程序配置.json
{
"auth": {
"clientId": "acb610688b49",
},
"cache": {
"cacheLocation": "localStorage"
},
"scopes": {
"loginRequest": ["openid", "profile", "user.read"]
},
"resources": {
"gatewayApi": {
"resourceUri": "https://localhost:44351/api",
"resourceScope": ["api://0e01a2d8/access_as_user"]
},
"msGraphProfile": {
"resourceUri": "https://graph.microsoft.com/v1.0/me",
"resourceScope": ["openid", "profile", "user.read"]
}
}
}
属性auth
和cache
由msal 配置 类型已知。属性scopes
和resources
未知。因此,我们正在尝试将 msal 配置的类型与自定义添加的属性合并。
- 可以有多个资源而不是此处显示的资源。
import * as Msal from 'msal'
import * as configJson from 'src/app-config.json'
interface ResourceInterface {
resourceUri: string
resourceScope: string | string[]
}
interface ResourcesInterface {
[key: string]: ResourceInterface
}
interface JsonConfigInterface {
auth: Msal.Configuration,
cache: Msal.Configuration,
scopes: {
loginRequest: string[]
}
resources: ResourcesInterface
}
const config: JsonConfigInterface = configJson as JsonConfigInterface
上面的界面失败并显示错误消息:
'{ auth: { clientId: string; 类型的转换 权限:字符串;重定向URI:字符串;postLogoutRedirectUri:字符串;}; 缓存:{缓存位置:字符串;}; 范围:{登录请求:字符串[];}; 资源:{ gatewayApi:{ ...; }; msGraphProfile: { ...; }; msGraphMail: { ...; }; msGraphGroupMember: { ...; }; }; }' 键入 'JsonConfigInterface' 可能是一个错误,因为这两种类型都没有与另一种充分重叠。如果这是故意的,请先将表达式转换为“未知”。属性“auth”的类型不兼容。'{ clientId: string; 类型中缺少属性 'auth' 权限:字符串;重定向URI:字符串;postLogoutRedirectUri:字符串;}' 但在类型 'Configuration'.ts(2352) Configuration.d.ts(89, 5) 中是必需的:'auth' 在这里声明。
我们是 TS 的新手,并试图弄清楚。为什么这些类型不能合并?我们做错了什么?
感谢您的帮助。
解决方案
Msal.Configuration 是
export type Configuration = {
auth: AuthOptions,
cache?: CacheOptions,
system?: SystemOptions,
framework?: FrameworkOptions
};
所以你不能说这种类型的身份验证是 Msal.Configuration。你应该尝试类似的东西
interface JsonConfigInterface extends Msal.Configuration {
scopes: {
loginRequest: string[]
},
resources: ResourcesInterface
}
身份验证和缓存已在 Msal.Configuration 中。如果你想缓存不是可选的,你应该这样做
interface JsonConfigInterface extends Msal.Configuration {
cache: Msal.CacheOptions,
scopes: {
loginRequest: string[]
},
resources: ResourcesInterface
}