假设我们有这段Typescript代码,如何最好地编写TODO部分?我和我的团队正在寻找一种优雅的方法来完成这个任务。
type MyType = {
key1?: string | null
key2?: string | null
key3?: string | null
// ...
// ...
// ...
};
type MyTypeNotNull = {
key1?: string
key2?: string
key3?: string
// ...
// ...
// ...
};
function logMyType(type: MyTypeNotNull) {
console.log(type);
}
const myType: MyType = {
key1: 'myKey1',
// key2 is omitted
key3: null,
// ...
// ...
// ...
};
const run = (value: MyType) => {
/* TODO
- throw when a prop is null
- make myType pass the type check of logMyType
*/
logMyType(value); // Error Type 'string | null | undefined' is not assignable to type 'string | undefined'
};
run(myType);
目前我们有一堆if
语句相互跟随,感觉应该有更好的方法来处理,你有什么简洁的建议吗?