我用TypeScript尝试了以下简单代码:
interface ListFavoritesParameters {
orderBy?: string
directionStr?: 'desc' | 'asc' | undefined
startAfter?: DocumentSnapshot
endBefore?: DocumentSnapshot
}
const listFavoritesDefaultParameters = {
orderBy: 'updated',
directionStr: 'desc'
}
const listFavorites = async (params: ListFavoritesParameters = listFavoritesDefaultParameters) => {
// ...
}
然后:
params: ListFavoritesParameters = listFavoritesDefaultParameters
VS Code用红色下划线标出,并在鼠标悬停时显示错误消息:
Type '{ orderBy: string; directionStr: string; }' is not assignable to type 'ListFavoritesParameters'.
Types of property 'directionStr' are incompatible.
Type 'string' is not assignable to type '"desc" | "asc" | undefined'.ts(2322)
为了使其正常工作,我通过以下方式更改了默认参数声明:
const listFavoritesDefaultParameters = {
orderBy: 'updated',
directionStr: 'desc' as "desc" | "asc" | undefined
}
这似乎很奇怪。有什么办法可以避免这种情况?
答案 0 :(得分:1)
当您声明带有字符串属性的对象文字时,该属性将被键入为string
:
const listFavoritesDefaultParameters = {
orderBy: 'updated',
directionStr: 'desc'
}
产生
// Intellisense type info:
const listFavoritesDefaultParameters: {
orderBy: string;
directionStr: string;
}
为避免自动类型扩展,可以声明'desc'
as const
:
const listFavoritesDefaultParameters = {
orderBy: 'updated',
directionStr: 'desc' as const
}
对于不支持as const
的旧TS版本,您也可以改用'desc' as 'desc'
。