发表于: 2017-06-30 23:08:59

1 1090


今天完成的事情:


关于检测对象文字赋值类型兼容中的问题:

interface TextOptions {
alignment?: string;
color?: string;
padding?: number;
}
function drawText(opts: TextOptions) { ... }

// None of these were errors before
drawText({ align: 'center' }); // Oops
drawText({ colour: 'grey' }); // Oops
drawText({ pading: 32}); // Oops

从1.6版本开始,对象文字中没有相应的属性将被标记为错误


drawText({align:' center ' }); //错误,在'TextOptions'中没有属性'align'


有时候想确保一些事件有正确的类型,但又有额外的属性。Type assertions (<T>v or v as T)不去检查额外的属性,可以使用它们代替类型注释:

interface Options {
x?: string;
y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = <Options>{ x: 'foo', y: 32, z: 100 };
// Still an error (good):
let q3 = <Options>{ x: 100, y: 32, z: 100 };


 一些API采取一个对象并动态地遍历其中的值,但是需要一定类型的“特殊”值。向类型添加字符串索引器,将会禁用额外的属性检查


interface Model {

name: string;

//修改后添加[others: string]: any;

}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});


举个栗子:

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
x = { move: 'catwalk', meow: 'mrar' };
} else {
x = { move: 'gallop', neigh: 'wilbur' };
}


声明一个变量X

let x: Dog|Cat|Horse;


或者:
x = <Dog>{ move: 'doggy paddle', woof: 'bark' };


interface DataModelOptions {
name?: string;
id?: number;
}
interface UserProperties {
[key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
/* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
/* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });


明天计划的事情:

继续学习


收获:

对象字面量中必须是已知属性。


对于 TypeScript 来说,直接赋值对象字符量,是按接口类型构造的一个新对象,它是 Named 接口类型的,所以这个对象字面量必须完全符合接口定义。


不过在 x = y 的时候,y 是已经构造出来的某个类型的对象,而且它的定义兼容 Named 接口,所以可以直接赋值给 x



返回列表 返回列表
评论

    分享到