Spe*_*cer 5 typescript typescript3.0
TypeScript (v3.2.2) 允许我定义接口的联合,每个接口都有一个唯一的字符串文字属性,可以用作类型保护,例如
type Device = Laptop | Desktop | Phone;
interface Laptop {
type: 'Laptop';
countDriveBays: number;
hasTouchScreen: boolean;
}
interface Desktop {
type: 'Desktop';
countDriveBays: number;
}
interface Phone {
type: 'Phone';
hasTouchScreen: boolean;
}
function printInfo(device: Device) {
if (device.type === 'Laptop') {
// device: Laptop
console.log(
`A laptop with ${device.countDriveBays} drive bays and ${
device.hasTouchScreen ? 'a' : 'no'
} touchscreen.`,
);
} else if (device.type === 'Desktop') {
// device: Desktop
console.log(`A desktop with ${device.countDriveBays} drive bays.`);
} else {
// device: Phone
console.log(`A phone with ${device.hasTouchScreen ? 'a' : 'no'} touchscreen.`);
}
}
Run Code Online (Sandbox Code Playgroud)
我想以isDeviceType通用方式编写一个函数:
const isDeviceType = <T extends Device['type']>(type: T) => {
return (device: Device): device is DeviceOf<T> => device.type === type;
}
// e.g.
const isPhone = isDeviceType('Phone');
isPhone({ type: 'Phone', hasTouchScreen: true }); // true
Run Code Online (Sandbox Code Playgroud)
但是,我定义DeviceOf类型的方式非常冗长,因为它列出了联合中的每个类型:
type DeviceOf<Type extends Device['type']> =
Type extends Laptop['type'] ? Laptop :
Type extends Desktop['type'] ? Desktop :
Type extends Phone['type'] ? Phone :
never;
Run Code Online (Sandbox Code Playgroud)
有没有更简洁的定义方式DeviceOf?我试过这些:
type DeviceOf<Type extends Device['type']> =
(infer D)['type'] extends Type ? D : never;
// TS2536: Type '"type"' cannot be used to index type 'D'.
// TS1338: 'infer' declarations are only permitted in the 'extends' clause of a conditional type.
// TS6133: 'D' is declared but its value is never read.
Run Code Online (Sandbox Code Playgroud)
type DeviceOf<Type extends Device['type']> =
(infer D) extends Device
? D['type'] extends Type
? D
: never
: never;
// TS1338: 'infer' declarations are only permitted in the 'extends' clause of a conditional type.
// TS6133: 'D' is declared but its value is never read.
// TS2304: Cannot find name 'D'.
Run Code Online (Sandbox Code Playgroud)
我的印象是错误 TS1338 是限制因素,因此DeviceOf在当前版本的 TypeScript 中不可能以通用方式定义。
Spe*_*cer 11
Found an alternative way, using just conditional types without the infer keyword:
type FindByType<Union, Type> = Union extends { type: Type } ? Union : never;
type DeviceOf<Type extends Device['type']> = FindByType<Device, Type>;
type Result = DeviceOf<'Laptop'>;
Run Code Online (Sandbox Code Playgroud)
Based on Ryan Cavanaugh's comment here: https://github.com/Microsoft/TypeScript/issues/17915#issuecomment-413347828
知道了。您必须应用“if”两次,一次用于创建infer类型,第二次用于检查infer类型是否扩展设备。只有在分支D extends Device你才能使用D['type']
type DeviceOf<Type extends Device['type']> =
Device extends (infer D) ?
D extends Device ?
D['type'] extends Type ? D : never : never : never;
type Result = DeviceOf<'Laptop'>;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1687 次 |
| 最近记录: |