[英]Merge typescript type and interface into one
我们正在尝试为下面的 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 Configuration Type知道。 属性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:字符串; }; 缓存:{缓存位置:字符串; }; 范围:{登录请求:字符串[]; }; 资源:{网关API:{...; }; 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
}
您应该键入auth
和cache
作为AuthOptions
和CacheOptions
,可以从Configuration.ts
导出,如您提供的链接所述。 这样,它将能够推断出哪些属性是必需的/可选的。
interface JsonConfigInterface {
auth: AuthOptions,
cache: CacheOptions,
scopes: {
loginRequest: string[]
}
resources: ResourcesInterface
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.