如何配置TypeScript来避免:类型'string'不能分配给类型'“ desc” | “ asc” | undefined'.ts(2322)?

时间:2020-08-21 23:19:56

标签: typescript

我用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
  }

这似乎很奇怪。有什么办法可以避免这种情况?

1 个答案:

答案 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'

相关问题