简体   繁体   English

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

[英]Type 'string' is not assignable to type 'A'

I have the following code snippet that does not compile:我有以下无法编译的代码片段:

interface A {
    a: string
}

export type SessionSsrProps<T> = Record<string, T> & {
    signOutUrl: string
}

const x: SessionSsrProps<A> = {
    x: {
        a: "Hello"
    },
    signOutUrl: "Hello"
}

the compiler complains:编译器抱怨:

Type 'string' is not assignable to type 'A'

What am I doing wrong?我究竟做错了什么?

I also tried:我也试过:


interface SessionSsrProps<T> {
    [key:string]: T
    signOutUrl: string
}

and the compiler complains:编译器抱怨:

Property 'signOutUrl' of type 'string' is not assignable to string index type 'T'.

I can't say confidently whether what you're doing is possible or not, but it's likely that it is not.我不能自信地说你正在做的事情是否可能,但很可能不是。

Both your attempts fail because you're describing an impossible type: a record with zero or more keys whose values are all of type T , AND also there is a key signOutUrl with a value of type string .您的两次尝试都失败了,因为您描述了一种不可能的类型:一条记录有零个或多个键,其值都是T类型,并且还有一个键signOutUrl的值类型为string This requires signOutUrl to satisfy both string & T , which is unresolvable given that T does not extend string .这需要signOutUrl同时满足string & T ,这是无法解决的,因为T不扩展string

What you want to express is a record with zero or more keys whose values are all of type T , EXCEPT the key signOutUrl which has a value of type string .您要表达的是具有零个或多个键的记录,其值都是T类型, signOutUrl值是string类型。 I believe (but am not certain) that this is not currently expressible in TypeScript.我相信(但不确定)这目前在 TypeScript 中无法表达。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM