Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

接口任意属性章节有误 #177

Open
Vicew opened this issue Jun 15, 2020 · 1 comment · May be fixed by #178
Open

接口任意属性章节有误 #177

Vicew opened this issue Jun 15, 2020 · 1 comment · May be fixed by #178

Comments

@Vicew
Copy link

Vicew commented Jun 15, 2020

章节地址

interface Person {
    name: string;
    age?: number;
    [propName: string]: string;
}

let tom: Person = {
    name: 'Tom',
    age: 25,
    gender: 'male'
};

// index.ts(3,5): error TS2411: Property 'age' of type 'number | undefined' is not assignable to string index type 'string'.
// index.ts(7,5): error TS2322: Type '{ name: string; age: number; gender: string; }' is not assignable to type 'Person'.
//   Property 'age' is incompatible with index signature.
//     Type 'number' is not assignable to type 'string'.

新的报错中我们可以看出接口的可选属性age的类型为number或者undefined,所以在后面作者用联合类型解决的时候需要多加一个undefined才正确

@Vicew Vicew linked a pull request Jun 15, 2020 that will close this issue
@CodeWielder
Copy link

CodeWielder commented Jul 27, 2021

同样是这个章节中。

一个接口中只能定义一个任意属性。

我感觉这里写的可能有点问题,不知道是否可以改为:任意属性的索引签名参数类型为 string 或者是 number

它们两个是可以同时存在的,比如:

interface C {
    [prop: string]: any;
    [propName: number]: any;
}

但是 number 必须是 string 的子集。

具体内容参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants