Skip to content

Commit cff7d02

Browse files
MSakamakidimadeveatii
authored andcommitted
add const assertions in typescript 3.4 (#26)
* syntax error of type alias * add const assertions * have done fixed * fix small reviews
1 parent 4592b19 commit cff7d02

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

README.md

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1199,6 +1199,77 @@ interface Config {
11991199
}
12001200
```
12011201

1202+
Case of Array, you can create a read-only array by using `ReadonlyArray<T>`.
1203+
do not allow changes such as `push()` and `fill()`, but can use features such as `concat()` and `slice()` that do not change the value.
1204+
1205+
**Bad:**
1206+
1207+
```ts
1208+
const array: number[] = [ 1, 3, 5 ];
1209+
array = []; // error
1210+
array.push(100); // array will updated
1211+
```
1212+
1213+
**Good:**
1214+
1215+
```ts
1216+
const array: ReadonlyArray<number> = [ 1, 3, 5 ];
1217+
array = []; // error
1218+
array.push(100); // error
1219+
```
1220+
1221+
Declaring read-only arguments in [TypeScript 3.4 is a bit easier](https://github.com/microsoft/TypeScript/wiki/What's-new-in-TypeScript#improvements-for-readonlyarray-and-readonly-tuples).
1222+
1223+
```ts
1224+
function hoge(args: readonly string[]) {
1225+
args.push(1); // error
1226+
}
1227+
```
1228+
1229+
Prefer [const assertions](https://github.com/microsoft/TypeScript/wiki/What's-new-in-TypeScript#const-assertions) for literal values.
1230+
1231+
**Bad:**
1232+
1233+
```ts
1234+
const config = {
1235+
hello: 'world'
1236+
};
1237+
config.hello = 'world'; // value is changed
1238+
1239+
const array = [ 1, 3, 5 ];
1240+
array[0] = 10; // value is changed
1241+
1242+
// writable objects is returned
1243+
function readonlyData(value: number) {
1244+
return { value };
1245+
}
1246+
1247+
const result = readonlyData(100);
1248+
result.value = 200; // value is changed
1249+
```
1250+
1251+
**Good:**
1252+
1253+
```ts
1254+
// read-only object
1255+
const config = {
1256+
hello: 'world'
1257+
} as const;
1258+
config.hello = 'world'; // error
1259+
1260+
// read-only array
1261+
const array = [ 1, 3, 5 ] as const;
1262+
array[0] = 10; // error
1263+
1264+
// You can return read-only objects
1265+
function readonlyData(value: number) {
1266+
return { value } as const;
1267+
}
1268+
1269+
const result = readonlyData(100);
1270+
result.value = 200; // error
1271+
```
1272+
12021273
**[⬆ back to top](#table-of-contents)**
12031274

12041275
### type vs. interface

0 commit comments

Comments
 (0)