类型“字符串”不可分配给类型

时间:2019-12-04 10:56:18

标签: typescript

const opts = {
    provider: 'SG',
    logLevel: 'info', // <--- here is what the error is referring to
    providerBaseUrl:
    ...

错误:

test/contract/api.provider.spec.ts:81:47 - error TS2345: Argument of type '{ provider: string; logLevel: string; providerBaseUrl: string; stateHandlers: { 'Has list of stations': () => Promise<string>; 'Has list of terminals': () => Promise<string>; 'Has list of centerlines': () => Promise<...>; }; ... 5 more ...; providerVersion: string; }' is not assignable to parameter of type 'VerifierOptions'.
  Types of property 'logLevel' are incompatible.
    Type 'string' is not assignable to type '"error" | "trace" | "debug" | "info" | "warn" | "fatal" | undefined'.

81             const output = await new Verifier(opts).verifyProvider();
                                                 ~~~~


Found 1 error.

为什么TypeScript抱怨。我显然是为该属性设置一个字符串值。

1 个答案:

答案 0 :(得分:0)

正如该问题下的注释所暗示的,这是因为string与字符串文字。

有两种/三种方法可以解决此问题:

// Type safe approach
const opts: VerifierOptions = {
    provider: 'SG',
    logLevel: 'info',

或者:

// Not type safe approach
const opts = {
    provider: 'SG',
    logLevel: 'info' as VerifierOptions['logLevel'],

如果需要使用变量:

// Not type safe approach
const opts = {
    provider: 'SG',
    logLevel: someVar as VerifierOptions['logLevel'],