我在打字稿上有点挣扎。假设你有一个字面量对象,它的值是用扩展运算符分配的:
const defaultState = () => {
return {
profile: {
id: '',
displayName: '',
givenName: '',
surName: '',
},
}
}
const state = reactive(defaultState())
const response = await getGraphProfile()
state.profile = { ...defaultState().profile, ...response.data }
更新类型库后@microsoft/microsoft-graph-types
,会引发以下 TS 错误:
TS2322: Type '{ accountEnabled?: Maybe<boolean>; ageGroup?: string | null | undefined; assignedLicenses?: MicrosoftGraph.AssignedLicense[] | undefined; assignedPlans?: MicrosoftGraph.AssignedPlan[] | undefined; ... 102 more ...; surName: string; }' is not assignable to type '{ id: string; displayName: string; givenName: string; surName: string; jobTitle: string; mail: string; mobilePhone: string; officeLocation: string; businessPhones: string[]; preferredLanguage: string; userPrincipalName: string; }'.
Types of property 'displayName' are incompatible.
Type 'string | null' is not assignable to type 'string'.
Type 'null' is not assignable to type 'string'.
尝试在此答案MicrosoftGraph.User
中设置文字对象上的接口并没有解决它,因为我必须在语法上做错了什么:
import * as MicrosoftGraph from '@microsoft/microsoft-graph-types'
const defaultState = () => {
return {
profile: MicrosoftGraph.User = {
id: '',
displayName: '',
givenName: '',
surName: '',
},
}
}
这会引发下面的 TS 错误,但该User
接口肯定存在并且在函数中正确使用getGraphProfile
。
TS2339:“typeof import”类型(“T:/Test/Brecht/Node/prod/hip-frontend/node_modules/@microsoft/microsoft-graph-types/microsoft-graph”)上不存在属性“用户”。
额外代码:
import config from 'src/app-config.json'
import axios, { AxiosRequestConfig } from 'axios'
import { getToken } from 'src/services/auth/authService'
import * as MicrosoftGraph from '@microsoft/microsoft-graph-types'
const callGraph = <T>(
url: string,
token: string,
axiosConfig?: AxiosRequestConfig
) => {
const params: AxiosRequestConfig = {
method: 'GET',
url: url,
headers: { Authorization: `Bearer ${token}` },
}
return axios.request<T>({ ...params, ...axiosConfig })
}
const getGraphDetails = async <T>(
uri: string,
scopes: string[],
axiosConfig?: AxiosRequestConfig
) => {
try {
const response = await getToken(scopes)
if (response && response.accessToken) {
return callGraph<T>(uri, response.accessToken, axiosConfig)
} else {
throw new Error('We could not get a token because of page redirect')
}
} catch (error) {
throw new Error(`We could not get a token: ${error}`)
}
}
export const getGraphProfile = async () => {
try {
return await getGraphDetails<MicrosoftGraph.User>(
config.resources.msGraphProfile.uri,
config.resources.msGraphProfile.scopes
)
} catch (error) {
throw new Error(`Failed retrieving the graph profile: ${error}`)
}
}
将财产保存为的正确方法是displayName
什么string | null
?