Skip to content
On this page
  • 对象字面量只能指定已知属性,如果有多出来的属性会提示错误
function logName(something: { name: string}) {
    console.log(something.name);
}
const params = {name:'zjh',age:19}
logName(params);
logName({name:'zjh',age:19}) //Error 'age' does not exist in type '{ name: string; }


通常,你会得到一个类似于 Type string is not assignable to type 'foo' 的错误,如下:

function iTakeFoo(foo: 'foo') {}
const test = {
   someProp: 'foo'
};

iTakeFoo(test.someProp); // Error: Argument of type string is not assignable to parameter of type 'foo'

这是由于 test 被推断为 { someProp: string },我们可以采用一个简单的类型断言来告诉 TypeScript 你想推断的字面量:

function iTakeFoo(foo: 'foo') {}

const test = {
 someProp: 'foo' as 'foo'
};

iTakeFoo(test.someProp); // ok

或者使用类型注解的方式,来帮助 TypeScript 推断正确的类型:

function iTakeFoo(foo: 'foo') {}

type Test = {
  someProp: 'foo';
};

const test: Test = {
  // 推断 `someProp` 永远是 'foo'
  someProp: 'foo'
};

iTakeFoo(test.someProp); // ok

参数数量

更少的参数数量是好的

const iTakeSomethingAndPassItAnErr = (x: (err: Error, data: any) => void) => {
 /* 做一些其他的 */
};

iTakeSomethingAndPassItAnErr(() => null); // ok
iTakeSomethingAndPassItAnErr(err => null); // ok
iTakeSomethingAndPassItAnErr((err, data) => null); // ok

// Error: 参数类型 `(err: any, data: any, more: any) => null` 不能赋值给参数类型 `(err: Error, data: any) => void`
iTakeSomethingAndPassItAnErr((err, data, more) => null);
  • never类型只能赋值给另外一个never

  • ThisType

as const

as const 跟readonly 作用一样: 引用

// read-only object
const config = {
 hello: 'world'
} as const;
config.hello = 'world'; // error

// read-only array
const array  = [ 1, 3, 5 ] as const;
array[0] = 10; // error

// You can return read-only objects
function readonlyData(value: number) {
 return { value } as const;
}

const result = readonlyData(100);
result.value = 200; // error