在Typescript中定义新类型时,哪个角色正在使用方括号和括号?在下面的例子中,应该是qazxsw poi变量数据的形状?
到目前为止,我玩了它并发现了以下内容。
typeThree
type typeOne = { [id: string] : string; };
type typeTwo = { id : string; };
type typeThree = { (id: string) : string; };
let varOne: typeOne[] = [{id:'', id2:''}]; // OK
let varTwo: typeOne[] = [{idd:''}]; // OK
let varThree: typeTwo[] = [{idd:''}]; // error
let varFour: typeTwo[] = [{id:'', id2:''}]; // error
let varFive: typeTwo[] = [{idd:''}]; // error
let varSix: typeTwo[] = [{id:''}]; // OK
似乎描述了一组地图,其键和值是字符串typeOne
似乎描述了一系列地图typeTwo
必须只包含一个名为{id: 'any string'}
的键id
我不知道它在描述什么。虽然您使用的是typeThree
关键字,但接口上的文档将适用于您的每个示例。 type
和type
都以同样的方式工作,但你不能使用interface
作为遗产。
允许带有任意字符串键的映射。在下面的示例中,键必须是一个字符串(type
,所以从技术上讲它是numbers are also allowed虽然不允许明确说明)并且值必须是一个字符串(并且只是一个字符串)。
id: string | number
索引器在手册的// Defines an indexer
// The id(or key) must be a string, or number.
// The value must be a string.
type TypeOne = { [id: string]: string; };
const a: TypeOne = {};
a['key'] = 'value';
// Example type violation Type '3' is not assignable to type 'string'
a['key'] = 3;
中描述。
您问题中的第二种类型是对象结构。它需要一个对象具有命名属性,并具有适当的类型值。当使用文字创建该类型的实例时,您将获得有关未知属性(不允许)的帮助,这有助于捕获错误拼写。
interface section
您问题中的第三种类型描述了一个功能。以下示例,包括示例type TypeTwo = { id: string; };
const a: TypeTwo = {
id: 'value'
}
// Object literal must only specify known values
const b: TypeTwo = {
id: 'value',
nmae: 'value'
}
// Type 'number' is not assignable to type 'string'.
const c: TypeTwo = {
id: 4
}
的有时神秘的情况,即使它没有b
参数也是有效的。关于那个的逻辑是,如果忽略函数体中的参数,为什么要在签名中强制它。调用代码可能会提供它,但无论如何你都没有使用它。
id
请参阅手册中的type TypeThree = (id: string) => string;
const a: TypeThree = (id: string) => {
return id;
};
const b: TypeThree = () => {
return 'value';
}
// Types of parameters 'id' and 'id' are incompatible.
const c: TypeThree = (id: number) => {
return 'value';
}
// Type 'number' is not assignable to type 'string'.
const d: TypeThree = (id: string) => {
return 5;
}
。