const car = { make: 'Honda', model: 'Accord', year: 1998 };
console.log('make' in car); //true
delete car.make;
if ('make' in car === false) {
car.make = 'Suzuki';
console.log(car.make); //Suzuki
typescript也是类似的
interface Admin {
name: string;
privileges: string[];
interface Employee {
name: string;
startDate: Date;
type UnknownEmployee = Employee | Admin;
function printEmployeeInformation(emp: UnknownEmployee) {
console.log("Name: " + emp.name);
if ("privileges" in emp) {
console.log("Privileges: " + emp.privileges);
if ("startDate" in emp) {
console.log("Start Date: " + emp.startDate);
2.2 typeof关键字
// “number”, “string”, “boolean” , “symbol”
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
if (typeof padding === "string") {
return padding + value;
throw new Error(`Expected string or number, got '${padding}'.`);
typeof 类型保护只支持两种形式:typeof v === "typename" 和 typeof v !== typename,"typename" 必须是 "number", "string", "boolean" 或 "symbol"。 但是 TypeScript 并不会阻止你与其它字符串比较,语言不会把那些表达式识别为类型保护。
2.3 instanceof 关键字
当联合类型中使用的是 class 而不是 interface 时,instanceof 语法就派上用场了,通过 instanceof 语法可以区分不同的 class 类型。
class Bird {
// 独有方法
fly() {};
// 共有方法
layEggs() {};
class Fish {
// 独有方法
swim() {};
// 共有方法
layEggs() {};
function getSmallPet(): Fish | Bird {
// ...
let pet = getSmallPet();
pet.layEggs(); // 正常
// 使用 in 语法进行
if (pet instanceof Bird) {
pet.fly()
} else {
pet.swim()
2.4 **自定义类型保护的类型谓词
function isNumber(x: any): x is number {
return typeof x === "number";
function isString(x: any): x is string {
return typeof x === "string";
function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
if (pagination.pageSize != _pagination.pageSize && (<ListObjProps<T, K>>listProps).pagination?.pageSize) {
localStorage.setItem(FeManagePageSize, _pagination.pageSize?.toString() || '10')